Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is element in array js

Following an old question, I still have a problem:

a = ["apple", "banana", "orange", "apple"];

a.indexOf("apple") = 0

What is the easiest way to find BOTH indexes of "apple" element in array? I want to delete them both at once - is it possible?

like image 362
Prosto Trader Avatar asked Feb 09 '14 17:02

Prosto Trader


2 Answers

That's the task for filter method:

var noApples = a.filter(function(el) { return el != "apple"; })
like image 199
c-smile Avatar answered Oct 30 '22 00:10

c-smile


What is the easiest way to find BOTH indexes of "apple" element in array?

You asked that, but also asked about deleting. I'll tackle indexes first, then deletion.

Indexes:

There's no shortcut, you have to loop through it. You can use a simple for loop:

var indexes = [];
var index;

for (index = 0; index < a.length; ++index) {
    if (a[n] === "apple") {
        indexes.push(index);
    }
});

Or two ES5 options: forEach:

var indexes = [];
a.forEach(function(entry, index) {
    if (entry === "apple") {
        indexes.push(index);
    }
});

Or reduce:

var indexes = a.reduce(function(acc, entry, index) {
    if (entry === "apple") {
        acc.push(index);
    }
    return acc;
}, []);

...although frankly that does't really buy you anything over forEach.

Deletion:

From the end of your question:

I want to delete them both at once - is it possible?

Sort of. In ES5, there's a filter function you can use, but it creates a new array.

var newa = a.filter(function(entry) {
    return entry !== "apple";
});

That basically does this (in general terms):

var newa = [];
var index;

for (index = 0; index < a.length; ++index) {
    if (a[n] !== "apple") {
        newa.push(index);
    }
});
like image 36
T.J. Crowder Avatar answered Oct 29 '22 22:10

T.J. Crowder