please tell me how to divide a two-dimensional array into N arrays. From this —>
{
name: ['name1', 'name2', 'name3', 'name4']
price: ['price1', 'price2', 'price3', 'price4']
}
need to get this —>
[
{name: name1, price: price1}
{name: name2, price: price2}
{name: name3, price: price3}
{name: name4, price: price4}
]
on a one-dimensional array, it works
function chunk(arr, size){
var chunkedArr = [];
var noOfChunks = Math.ceil(arr.length/size);
console.log(noOfChunks);
for(var i=0; i<noOfChunks; i++){
chunkedArr.push(arr.slice(i*size, (i+1)*size));
}
return chunkedArr;
}
var chunkedArr = chunk(priceArr, 1);
2
Answers
Use
map()
ondata.name
, use theindex
provided bymap
to get his buddy-price.You can
reduce()
theObject.entries
and then add to each object in the result array. This will work for any number of keys in the input object (and even keys with different length value arrays). Here using nullish coalescing assignment (??=) to ensure an object exists at each index before setting each property.Mismatched input example