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?
That's the task for filter method:
var noApples = a.filter(function(el) { return el != "apple"; })
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.
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
.
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);
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With