1

Say that I have an array containing strings:

var array = ["test","apple","orange","test","banana"];

and some strings are exactly the same (test). Say that I want to get all the indexes in the array where the string test is located in the array and not just the first indexOf. Is there a nice solution to this problem that is as fast as possible and not using jQuery, I.E getting 0,2 as a result?

Thanks

user1825441
  • 507
  • 9
  • 13
  • 1
    This sounds exactly like your problem http://stackoverflow.com/questions/20798477/how-to-find-index-of-all-occurrences-of-an-element-in-array – leopik Oct 02 '14 at 07:43

1 Answers1

0

You can use the builtin Array.prototype.forEach like this

var indices = [];

array.forEach(function(currentItem, index) {
    if (currentItem === "test") {
        indices.push(index);
    }
});

console.log(indices);

Even better you can use Array.prototype.reduce like this

var indices = array.reduce(function(result, currentItem, index) {
    if (currentItem === "test") {
        result.push(index);
    }
    return result;
}, []);

console.log(indices);

Since you want the solution to be even working in IE, you might want to go with the plain old loop, like this

var indices = [], i;

for (i = 0; i < array.length; i += 1) {
    if (array[i] === "test") {
        indices.push(i);
    }
}

console.log(indices);
thefourtheye
  • 233,700
  • 52
  • 457
  • 497