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 a result, the array categoriescontains a unique list of product categories.

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

If not, then it probably makes no sense to use it map()first. 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 , , . , , . , . , . , , , . ,

+4
4

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

: 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>');
+5

mapall object category values ​​first, then use filterto remove 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

+2
source

Follow the answer below SO:

How to get individual 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);
}
0
source

Source: https://habr.com/ru/post/1621732/


All Articles