How do I group the array via javascript to just
- Vehicles
- Food
I cant seem to figure it out via "reduce" since the array has no "key" to specify.
Thank you
CodePudding user response:
const group1 = arr.filter(item => item === 'Vehicles');
const group2 = arr.filter(item => item === 'Food');
Or if you want a general solution:
let groups = {};
for (const item of arr) {
if (!groups[item]) groups[item] = [];
groups[item].push(item);
}
CodePudding user response:
I think I don't get your question completely, but if you are trying to remove duplicates, this could be an option
const originalArray = ["vehicle", "food", "vehicle", "food", "vehicle", "food"];
const noDuplicates = new Set(originalArray);
console.log(Array.from(noDuplicates));