-1

I would like to filter the following arrays

[
    {
        index: 4,
        name: "car",
        price: [10,20,30]
    },
    {
        index: 4,
        name: "car",
        price: [40,50,60]
    },
    {
        index: 3,
        name: "bike",
        price: [40,50,60]
    },
    {
        index: 2,
        name: "scooter",
        price: [10,20,60]
    },
    {
        index: 2,
        name: "scooter",
        price: [70]
    },
]

so that the output looks like this

[
    {
        index: 4,
        name: car,
        price: [40,50,60,10,20,30]
    },
    {
        index: 3,
        name: bike,
        price: [40,50,60]
    },
    {
        index: 2,
        name: scooter,
        price: [10,20,60, 70]
    }
]

Objects that have the same name and index, connect, i.e. connect the price array.

I can filter this array but I don't know how to connect price array. Code in codesanbox

Elder
  • 341
  • 3
  • 8
  • 21
  • Does this answer your question? [How can I group an array of objects by key?](https://stackoverflow.com/questions/40774697/how-can-i-group-an-array-of-objects-by-key) – jabaa Aug 29 '23 at 15:39
  • 1
    You want to group the elements, not filter. – jabaa Aug 29 '23 at 15:39

1 Answers1

0

I sort the array so that items with the same index are side by side. I can then go through the array and if the previous item has the same index, I merge.

I do an in-place sort, but if you prefer immutability:

data = [...data].sort((a,b) => a.index - b.index);

var data = [
    {
        index: 4,
        name: "car",
        price: [10,20,30]
    },
    {
        index: 4,
        name: "car",
        price: [40,50,60]
    },
    {
        index: 3,
        name: "bike",
        price: [40,50,60]
    },
    {
        index: 2,
        name: "scooter",
        price: [10,20,60]
    },
    {
        index: 2,
        name: "scooter",
        price: [70]
    },
];

data.sort((a,b) => a.index - b.index);
let result = [];
for (const [idx, item] of data.entries()) {
    if (idx === 0) {
        result.push(item);
    }
    else {
       let previous = result[result.length-1];
        if (previous.index === item.index) {
            let newItem = { ...item, price: item.price.concat(previous.price) };
            result[result.length-1] = newItem;
        } else {
            result.push(item);
        }
    }
}

document.write(JSON.stringify(result));
scrhartley
  • 676
  • 7