Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
144
rated 0 times [  145] [ 1]  / answers: 1 / hits: 36229  / 9 Years ago, fri, december 25, 2015, 12:00:00

Essentially, I want to implement the following:



var categories = [];
var products = // some array of product objects
products.map(function(value) {
if(categories.indexOf(value.Category === -1)) categories.push(value.Category);
});


As result, categories array contains unique list of product categories.



I feel that there should be a better way to do it, but nothing comes to mind.



If there isn't then probably there is no point to use map() in the first place. I could do as simple as



var categories = [];
var products = // some array of product objects
for (var i = 0; i < products.length; i++) {
if(categories.indexOf(products[i].Category === -1)) categories.push(products[i].Category);
}


UPDATE for those who insist it's a duplicate of how to make an array unique question. I saw that post, and for my situation I don't think it applies. I don't have an array of values that I need to make unique. I have an array of objects and I need to build an array of unique values. The difference might be subtle - but to get to the use case of that topic I would build a non-unique array and then make it unique. Seems even worse than my original solution


More From » arrays

 Answers
17

you can use reduce instead of map



var products = [{Category:'vegetable', price: 1}, {Category:'fruits', price: 2}];
var categories = products.reduce(function(sum, product) {
if(sum.indexOf(product.Category) === -1){
sum.push(product.Category);
}
return sum;
}, []);

[#63945] Wednesday, December 23, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
maleahp

Total Points: 223
Total Questions: 102
Total Answers: 116

Location: Sao Tome and Principe
Member since Wed, Dec 29, 2021
2 Years ago
;