The Walrus
The Walrus

Reputation: 1208

filter n number of times on an array

I want to recreate filters that online shops have if someone wants to select says 'tshirts' and in 'green'. clearly that is easy. However, if they select multiple colours, how can I do this?

I know I can chain like this: colors.filter(col => col.name =='green' || col.name =='black'), but what if I wanted 10 colours selected or 20, this is currently not very scalable. Can I map over the colours in some way and then filter?

I tried this but it did not work:

colors = ['black', 'red']
col = [{name: 'green'}, {name: 'black'}, {name: 'red'}]
colors.forEach((c) => col.filter((ca) => ca.name === c))`

Upvotes: 2

Views: 193

Answers (5)

Ankit Agarwal
Ankit Agarwal

Reputation: 30739

You can create a new array for your final result called selectedColor so that objects are pushed with matching color.

colors = ['black', 'red'];
col = [{name: 'green'}, {name: 'black'}, {name: 'red'}];
var selectedColor = [];
colors.forEach((c) => col.filter((ca) => {
   if(ca.name === c){
     selectedColor.push(ca);
   }
}));
console.log(selectedColor);

USING indexOf()

colors = ['black', 'red']
col = [{name: 'green'}, {name: 'black'}, {name: 'red'}]
var selected = col.filter(prod => colors.indexOf(prod.name) !== -1)
console.log(selected);

Using indexOf() is highly encouraged as includes() do not work in IE browsers.

Upvotes: 0

Mihai Alexandru-Ionut
Mihai Alexandru-Ionut

Reputation: 48417

If they select multiple colours, how can I do this?

You can use includes() or indexOf() methods.

colors = ['black', 'red']
col = [{name: 'green'}, {name: 'black'}, {name: 'red'}]
var selected = col.filter(prod => colors.includes(prod.name))
console.log(selected);

Upvotes: 4

epascarello
epascarello

Reputation: 207537

You should use filter and includes

const colors = ['black', 'red']
const col = [{name: 'green'}, {name: 'black'}, {name: 'red'}]
let filtered = col.filter(ca => colors.includes(ca.name))
console.log(filtered)

Upvotes: 0

Faly
Faly

Reputation: 13356

You can use array.includes:

colors = ['black', 'red']
cols = [{name: 'green'}, {name: 'black'}, {name: 'red'}];

var filtered = cols.filter(c => colors.includes(c.name));
console.log(filtered);

Upvotes: 0

Máté Safranka
Máté Safranka

Reputation: 4106

You can just use a Set:

let filterColors = new Set();
filterColors.add('green');
filterColors.add('black');

colors.filter(col => filterColors.has(col.name));

Upvotes: 5

Related Questions