Reputation: 1509
I have an array of objects that I am filtering. I don't want the first element in the array to be removed in the filter.
For example, the array (oData
) may look like this:
[
{id: "abc1", type: "car"},
{id: "h445", type: "car"},
{id: "kjj6", type: "van"},
{id: "5yee", type: "bus"}
]
I'm applying a filter to remove elements where the type is in a list of user selected options as follows:
this.dataSet = this.oData.filter((d) => this.sOptions.includes(d.type));
If the user has selected 'van' and 'bus', the dataset looks like this:
[
{id: "kjj6", type: "van"},
{id: "5yee", type: "bus"}
]
However, I want the first element {id: "abc1", type: "car"}
to always remain, i.e I want it to be excluded from the filter.
I have tried filtering and then using unShift() to add it back in but it is behaving strangely.
Is there a better way to do this?
Upvotes: 0
Views: 1372
Reputation: 2708
There's a 2nd argument passed to the filter callback that represents the index of the current item. You can use to exclude the first element.
let data = [
{id: "abc1", type: "car"},
{id: "h445", type: "car"},
{id: "kjj6", type: "van"},
{id: "5yee", type: "bus"}
];
let selectedOptions = [
"van",
"bus"
]
let filtered = data.filter((item, idx) => {
return idx === 0 || selectedOptions.indexOf(item.type) > -1;
});
console.log(JSON.stringify(filtered));
//PRINTS: [{"id":"abc1","type":"car"},{"id":"kjj6","type":"van"},{"id":"5yee","type":"bus"}]
Upvotes: 2
Reputation: 3920
In ES6, you can do it like this
var arr2 = this.oData.filter(a => a.type == "van" || a.type == "bus");
this.dataSet = [this.oData[0], ...arr2];
Upvotes: 0
Reputation: 2268
You could do it like this:
arr.filter(num => num !== arr[0] && yourConditionHere)
Upvotes: 1