0

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']
  • Are you asking for a function that deletes duplicates? Did you search? There are many Q&A about that already.... – trincot Mar 20 '21 at 10:57
  • 2
    @trincot - I don't read it that way, but I can see how someone would. Taner - What result would you expect on `["banana", "apple", "pear", "apple", "orange", "apple"]`? – T.J. Crowder Mar 20 '21 at 11:00
  • The OP should answer that. – trincot Mar 20 '21 at 11:08
  • 1
    If there are three `"apples"` in the array should it still only return one? – pilchard Mar 20 '21 at 11:08
  • The question means that `only one element should be removed`. I do not know why the question was closed. I am waiting for @Taner for explanation. – wittgenstein Mar 20 '21 at 11:10
  • 2
    That isn't clear @wittgenstein. In the example case removing one also has the effect of making it unique. – pilchard Mar 20 '21 at 11:11
  • @ Taner - Stack Overflow is a **very** active place, even on the weekend. When you post a question (or an answer), *stick around* for a few minutes so you can respond to anything that comes up in the comments. – T.J. Crowder Mar 20 '21 at 11:27
  • Either way, it is a duplicate question. – trincot Mar 20 '21 at 12:19

3 Answers3

3

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.

T.J. Crowder
  • 879,024
  • 165
  • 1,615
  • 1,639
0

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);
})
Niraeth
  • 170
  • 1
  • 4
  • 1
    *"...to delete only 1 of them..."* doesn't sound like "remove duplicates" to me. But if so, yes, this is good enough for a small array. Lots of repeated searching, though, so scales not very well. – T.J. Crowder Mar 20 '21 at 10:58
0

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);
Nina Scholz
  • 323,592
  • 20
  • 270
  • 324