-4

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.

2
  • 1
    What have you tried so far? Where are you stuck? Commented Apr 9, 2024 at 6:53
  • jsperf.app/xiqaqi Commented Apr 9, 2024 at 7:19

1 Answer 1

-3

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);

Sign up to request clarification or add additional context in comments.

1 Comment

Is this done with chat GPT?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.