Reduce array to get key and value - Javascript Array

Javascript examples for Array:reduce

Description

Reduce array to get key and value

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript">
    window.onload=function(){/*from w  w w  . jav a2s  . c om*/
var myArray = [1, 1, 2, 3, 3];
var itemsObj = myArray.reduce((p, c) => {
  const key = `Order_Items_${c}`;
  p[key] = p[key] || [];
  p[key].push(c)
  return p;
}, {});
console.log(JSON.stringify(itemsObj, null, 2));
    }

      </script> 
   </head> 
   <body>  
   </body>
</html>

Related Tutorials