Javascript indexOf method with multiple values

人走茶凉 提交于 2019-12-10 14:52:10

问题


I have an array wich contains multiple same values

["test234", "test9495", "test234", "test93992", "test234"]

Here I want to get the index of every test234 in the array

For that I've tried Array.prototype.indexOf() method. But It only returns me 0 but I want it to return me [0, 2, 4].

How can I do that?

var array = ["test234", "test9495", "test234", "test93992", "test234"];
document.write(array.indexOf("test234"));

回答1:


Just make it a for loop to check each array element.

var array = ["test234", "test9495", "test234", "test93992", "test234"];

for (i=0;i<array.length;i++) {
  if (array[i] == "test234") {
    document.write(i + "<br>");
  }
}



回答2:


This kind of function doesn't exist built in, but it would be pretty easy to make it yourself. Thankfully, indexOf can also accept a starting index as the second parameter.

function indexOfAll(array, searchItem) {
  var i = array.indexOf(searchItem),
      indexes = [];
  while (i !== -1) {
    indexes.push(i);
    i = array.indexOf(searchItem, ++i);
  }
  return indexes;
}

var array = ["test234", "test9495", "test234", "test93992", "test234"];
document.write(JSON.stringify(indexOfAll(array, "test234")));



回答3:


You can use the fromIndex of Array#indexOf.

fromIndex

The index to start the search at. If the index is greater than or equal to the array's length, -1 is returned, which means the array will not be searched. If the provided index value is a negative number, it is taken as the offset from the end of the array. Note: if the provided index is negative, the array is still searched from front to back. If the calculated index is less than 0, then the whole array will be searched. Default: 0 (entire array is searched).

~ is a bitwise not operator.

It is perfect for use with indexOf(), because indexOf returns if found the index 0 ... n and if not -1:

value  ~value   boolean
-1  =>   0  =>  false
 0  =>  -1  =>  true
 1  =>  -2  =>  true
 2  =>  -3  =>  true
 and so on 

var array = ["test234", "test9495", "test234", "test93992", "test234"],
    result = [],
    pos = array.indexOf('test234');

while (~pos) {
    result.push(pos);
    pos = array.indexOf('test234', pos + 1); // use old position incremented
} //                               ^^^^^^^

document.write('<pre> ' + JSON.stringify(result, 0, 4) + '</pre>');



回答4:


You may use indexOf with a for loop to get the index values of 0,2,4:

var array = ["test234", "test9495", "test234", "test93992", "test234"];
let newArr=[];
for (i=0;i<array.length;i++) {
  if (array[i].indexOf("test234") >=0 ) {
    newArr.push(i);
  }
}
document.write(newArr);



回答5:


You can use reduce:

const indexesOf = (arr, item) => 
  arr.reduce(
    (acc, v, i) => (v === item && acc.push(i), acc),
  []);

So:

const array = ["test234", "test9495", "test234", "test93992", "test234"];
console.log(indexesOf(array, "test234")); // [0, 2, 4]

An alternative approach could be having an iterator:

function* finder(array, item) {
  let index = -1;
  while ((index = array.indexOf(item, index + 1)) > -1) {
    yield index;
  }
  return -1;
}

That's give you the flexibility to have the search in a lazy way, you can do it only when you need it:

let findTest234 = finder(array, "test234");

console.log(findTest234.next()) // {value: 0, done: false}
console.log(findTest234.next()) // {value: 2, done: false}
console.log(findTest234.next()) // {value: 4, done: false}    
console.log(findTest234.next()) // {value: -1, done: true}

Of course, you can always use it in loops (since it's an iterator):

let indexes = finder(array, "test234");

for (let index of indexes) {
   console.log(index);
}

And consume the iterator immediately to generate arrays:

let indexes = [...finder(array, "test234")];
console.log(indexes); // [0, 2, 4]

Hope it helps.



来源:https://stackoverflow.com/questions/36631641/javascript-indexof-method-with-multiple-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!