In an array of objects, I want to remove all objects that don't have a certain property.
This is what I tried so far:
myArray.splice(myArray.findIndex(item => item.myProperty === null), 1)
It doesn't seem to work. What should I do instead?
In an array of objects, I want to remove all objects that don't have a certain property.
This is what I tried so far:
myArray.splice(myArray.findIndex(item => item.myProperty === null), 1)
It doesn't seem to work. What should I do instead?
Whenever you have an array and you want to remove certain items think of it as a 'filtering' problem
const hasProp = prop => item => {
// if the prop is in the item, returns true
return prop in item;
}
// filter takes a predicate function (1 param, returns true/false)
// filter is 'immutable' i.e. returns a new array
const filteredArray = myArray.filter(hasProp('myProperty'))
The above creates a re-usable filtering function (higher order function). It can also be written in a less re-usable (less functional programming) way:
const filteredArray = myArray.filter( item => {
return 'myProperty' in item;
})
You can use filter
to remove the items. The final returned array will contain the required values.
const fruits = [
{ color: 'yellow', name: 'banana' },
{ color: 'yellow', name: 'mango' },
{ color: 'green', name: 'guava' }
];
const colorToRemove = 'yellow';
const filteredFruit = fruits.filter((item) => item.color !== colorToRemove);
console.log(filteredFruit);