Search code examples
javascriptarraysreduce

Create array based on nested array


I have an array like that

const arr = [ [1, 0], [0, 2], [0, 1], [0, 1] ]

I want to reduce it and get a new array. My aim is getting values of nested array by index. [[index(0)],[index(1)]

const new arr = [ [1,0,0,0] , [0,2,1,1] ]

I tried but I don't understand how i can it.


Solution

  • You can use below code:

    const arr = [
      { date: '2024/02/05', price: '1400' },
      { date: '2024/02/06', price: '1400' },
      { date: '2024/02/07', price: '2000' },
      { date: '2024/02/08', price: '2000' },
      { date: '2024/02/09', price: '2000' },
      { date: '2024/02/10', price: '2500' },
      { date: '2024/02/11', price: '2500' }
    ];
    
    const groupedArr = arr.reduce((acc, obj) => {
      const existingItem = acc.find(item => item.price === obj.price);
      if (existingItem) {
        existingItem.date.push(obj.date);
      } else {
        acc.push({ price: obj.price, date: [obj.date] });
      }
      return acc;
    }, []);
    
    console.log(groupedArr);