简体   繁体   中英

how to exclude some elements from javascript Array.map() callback

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

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;
}, []);

Update: A solution with Array.prototype.reduce()

 var products = [{ Name: 'milk', price: 2.50, Category: 'groceries' }, { Name: 'shirt', price: 10, Category: 'clothing' }, { Name: 'apples', price: 5, Category: 'groceries' }], categories = products.reduce(function (r, a) { if (!~r.indexOf(a.Category)) { r.push(a.Category); } return r; }, []); document.write('<pre>' + JSON.stringify(categories, 0, 4) + '</pre>'); 

map all the values of the object categories out first, then use filter to dispose of the duplicates.

var products = [
  { category: 'A' },
  { category: 'B' },
  { category: 'A' },
  { category: 'D' }
];

var categories = products.map(function (e) {
  return e.category;
}).filter(function (e, i, a) {
  return a.indexOf(e) === i;
}); // [ "A", "B", "D" ]

DEMO

Follow the Below SO Answer:

How to get distinct values from an array of objects in JavaScript?

var flags = [], output = [], l = array.length, i;
for( i=0; i<l; i++) {
    if( flags[array[i].age]) continue;
    flags[array[i].age] = true;
    output.push(array[i].age);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM