Reputation: 373
I am attempting to filter out array data
and have my return be newData
filtering out the index that includes the title "Tourism"
I am using the .filter
method and using .includes
but when doing so newData return value includes "Tourism" even though I putting a check to return all values that does not include this.
Here is a code example of what I am working with :
let data = [ { title: "Vacation", revenue: 23421 }, { title: "Hospitals", revenue: 34212 }, { title: "Tourism", revenue: 42124 }, {title: "International Tourism", revenue: 87321 } ]
newData = data.filter(function (item) {
return !item.title.includes('Tourism') || item.title.includes('Vacation')
})
console.log(newData)
I am expecting the returning values to not include "Tourism" and "International Tourism"
based off the .includes
returning everything that does not include "Tourism". Am I approaching this scenario the correct way? My current value is returning everything within the array regardless of my .includes
check
Upvotes: 0
Views: 90
Reputation: 4595
includes
is a method, so it is a function which takes an argument, specifically the value to check for in the string or array it is called on. Use .includes(value)
instead:
let data = [{
title: "Vacation",
revenue: 23421
}, {
title: "Hospitals",
revenue: 34212
}, {
title: "Tourism",
revenue: 42124
}, {
title: "International Tourism",
revenue: 87321
}];
newData = data.filter(
item => !item.title.includes('Tourism')
);
console.log(newData);
For your edit, if you want to filter out multiple values, you can use a few ways to say the same thing. Consider !includesTitle() && !includesVacation()
("doesn't include title and doesn't include vacation") and !(includesTitle() || includesVacation)
("doesn't include title or location"), which are semantically equivalent:
let data = [ { title: "Vacation", revenue: 23421 }, { title: "Hospitals", revenue: 34212 }, { title: "Tourism", revenue: 42124 }, {title: "International Tourism", revenue: 87321 } ];
// filter for items where item doesn't include 'tourism' or 'vacation'
newData = data.filter(
// using ! to exclude any that match:
item => !(
// Tourism, OR
item.title.includes('Tourism') ||
// Vacation
item.title.includes('Vacation')
)
);
console.log(newData);
Upvotes: 2