Skip to content
Advertisement

Create array of arrays from array of objects in the style of a matrix

I have an array of objects. I am trying to create a matrix-like array of objects.

This is my code:

let data = [
    {device: 'iphone',   site: 'google', val1:10, val2:20, val3:30},
    {device: 'iphone',   site: 'bing',   val1:23, val2:12, val3:14},
    {device: 'iphone',   site: 'jeeves', val1:67, val2:78, val3:12},
    {device: 'ipad',     site: 'google', val1:10, val2:20, val3:30},
    {device: 'ipad',     site: 'bing',   val1:23, val2:12, val3:14},
    {device: 'ipad',     site: 'jeeves', val1:67, val2:78, val3:12}
    ];

let arr = data.map(d => Object.values(d));
console.log(arr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

When I do the map like above, I am getting all the object values into the array of arrays.

How do I make my data look like this:

    arr = [
        [0,0,67], [0,1,23],[0,2,10],[0,3,67],[0,4,23],[0,5,10],
        [1,0,78], [1,1,12],[1,2,20],[1,3,78],[1,4,12],[1,5,20],
        [2,0,12], [2,1,14],[2,2,30],[2,3,12],[2,4,14],[2,5,30],
        ]

Not sure how to make my array objects look like the matrix above.

Advertisement

Answer

To get just the numeric values from each object use Array.filter(), and ignore value that are NaN (not a number):

const data = [{"device":"iphone","site":"google","val1":10,"val2":20,"val3":30},{"device":"iphone","site":"bing","val1":23,"val2":12,"val3":14},{"device":"iphone","site":"jeeves","val1":67,"val2":78,"val3":12},{"device":"ipad","site":"google","val1":10,"val2":20,"val3":30},{"device":"ipad","site":"bing","val1":23,"val2":12,"val3":14},{"device":"ipad","site":"jeeves","val1":67,"val2":78,"val3":12}];

const arr = data.map(d => Object.values(d).filter(v => !isNaN(v)));

console.log(arr);

To get your matrix – reverse the array, map the objects, and then map the values after filtering them, and use the indexes. Flatten the results one level, and sort according to the 1st value of each sub-array in the matrix.

const data = [{"device":"iphone","site":"google","val1":10,"val2":20,"val3":30},{"device":"iphone","site":"bing","val1":23,"val2":12,"val3":14},{"device":"iphone","site":"jeeves","val1":67,"val2":78,"val3":12},{"device":"ipad","site":"google","val1":10,"val2":20,"val3":30},{"device":"ipad","site":"bing","val1":23,"val2":12,"val3":14},{"device":"ipad","site":"jeeves","val1":67,"val2":78,"val3":12}];

const arr = [...data]
  .reverse()
  .map((d, y) => 
    Object.values(d)
      .filter(v => !isNaN(v))
      .map((v, x) => [x, y, v])
  )
  .flat(1)
  .sort(([a], [b]) => a - b);
  
console.log(arr);
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement