skip to Main Content

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


  1. Use map() on data.name, use the index provided by map to get his buddy-price.

    const data = {
        name: ['name1', 'name2', 'name3', 'name4'],
        price: ['price1', 'price2', 'price3', 'price4']
    };
    
    const res = data.name.map((name, i) => ({ name, price: data.price[i] }));
    console.log(res);
    Login or Signup to reply.
  2. You can reduce() the Object.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.

    const input = {
      name: ['name1', 'name2', 'name3', 'name4'],
      price: ['price1', 'price2', 'price3', 'price4'],
    };
    
    const result = Object.entries(input).reduce((a, [k, vs]) => {
      for (const [i, v] of vs.entries()) {
        (a[i] ??= {})[k] = v;
      }
    
      return a;
    }, []);
    
    console.log(result);

    Mismatched input example

    const input = {
      id: ['id1', 'id2', 'id3', 'id4', 'id5'],
      name: ['name1', 'name2', 'name3', 'name4'],
      price: ['price1', 'price2'],
    };
    
    const result = Object.entries(input).reduce((a, [k, vs]) => {
      for (const [i, v] of vs.entries()) {
        (a[i] ??= {})[k] = v;
      }
    
      return a;
    }, []);
    
    console.log(result);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search