so I have an array of values like this
const foodsList = [
{
foodOrigin: "Padang",
foodCode: "SPI",
foodName: "Nasi Padang"
},
{
foodOrigin: "Padang",
foodName: "Gulai",
originCode: "PDN"
},
{
foodOrigin: "Padang",
foodName: "Rendang",
originCode: "PDN"
},
{
foodOrigin: "Palembang",
foodName: "Pempek",
originCode: "PLG"
},
{
foodOrigin: "Palembang",
foodName: "Tekwan",
originCode: "PLG"
},
{
foodOrigin: "Yogyakarta",
foodName: "Gudeg",
originCode: "YKT"
}
];
and I want to filter the array so the result would be like this instead
const filteredFoodsList = [
{
foodOrigin: "Padang",
originCode: "PDN"
},
{
foodOrigin: "Palembang",
originCode: "PLG"
},
{
foodOrigin: "Yogyakarta",
originCode: "YKT"
}
];
In order to achieve the result, I tried doing it like below but is there a cleaner and better way to do this? ( especially since my actual array’s data consist of more than 500 )
const filteredFoodsList = [];
for (let i = 0; i < foodsList.length; i++) {
if (i === 0) {
filteredFoodsList.push({
originCode: foodsList[i].originCode,
foodOrigin: foodsList[i].foodOrigin
});
}
let isExist = false;
for (let j = 0; j < filteredFoodsList.length; j++) {
if (foodsList[i].originCode === filteredFoodsList[j].originCode) {
isExist = true;
}
}
if (!isExist) {
filteredFoodsList.push({
originCode: foodsList[i].originCode,
foodOrigin: foodsList[i].foodOrigin
});
}
}
5
Answers
As the OP stated there should be some focus on performance, so..
The
Map
could be the fastest way to collect unique values.(I’ve borrowed
Array.from(map, ([originCode, foodOrigin]) => ({ foodOrigin, originCode }))
from Nina’s answer, really ellegant).But it doesn’t affect the performance since the resulting array should be quite small.
But she forgot to include a
Map::has()
check that really improves the performance significantly.What’s important how fast the source array is iterated. As always I see there can’t be a faster thing then
for(let i = 0; ...)
…And a benchmark:
You can use an object to store the values
You could take a
Map
and get a new array from it.Here’s my "old-fashioned" approach without
Map
usage:+ + + explanation in progress + + +