I have 2 apples in array. Filter method deletes all apples. Is there a way to delete only 1 of them.
var box = ['banana', 'apple', 'apple']
Output that I'm expectig:
box.filter((a) => a !== 'apple') => ['banana', 'apple']
I have 2 apples in array. Filter method deletes all apples. Is there a way to delete only 1 of them.
var box = ['banana', 'apple', 'apple']
Output that I'm expectig:
box.filter((a) => a !== 'apple') => ['banana', 'apple']
Nothing built-in, no. You can remember whether you've seen it and always return true
afterward:
const box = ["banana", "apple", "apple"];
let seenApple = false;
const filtered = box.filter((a) => {
if (seenApple) {
return true;
}
seenApple = a === "apple";
return !seenApple;
});
console.log(filtered);
Alternatively you could find the index of the first apple
:
const appleIndex = box.findIndex(a => a === "apple");
...and then either filter
by that index:
const filtered = box.filter((entry, index) => index !== appleIndex);
...or use splice
to modify the array in-place.
Are you looking to remove duplicates? If you just want an array with unique elements, you can do something like this
var unique_arr = arr.filter(function(elem, index, self) {
return index === self.indexOf(elem);
})
You could take a closure with another variable for overriding the condition.
const
box = ['banana', 'apple', 'apple'],
result = box.filter(
(found => a => a !== 'apple' || found || !(found = true))
(false)
);
console.log(result);