簡體   English   中英

如何在javascript數組中搜索相同值的多個索引

[英]How to search for multiple index(es) of same values in javascript array

我有一個1維數組,如:

var abc = ['a','a','b','a','c']

現在我想找回'a'所有索引,即0,1和3。

有沒有簡單的解決方案?

PS

我知道IndexOfjQuery.inArray() 但他們只返回了第一個匹配元素的索引

您可以使用以下方法擴展基本Array Object

Array.prototype.multiIndexOf = function (el) { 
    var idxs = [];
    for (var i = this.length - 1; i >= 0; i--) {
        if (this[i] === el) {
            idxs.unshift(i);
        }
    }
    return idxs;
};

然后操作

var abc = ['a','a','b','a','c'];
abc.multiIndexOf('a');

會給你結果:

[0, 1, 3]

Jsperf比較 unshift / push / push(逆序)

您可以使用與indexOf結合的while循環,而不是使用for循環:

var array = [1, 2, 3, 4, 2, 8, 5],
    value = 2,
    i = -1,
    indizes = [];

while((i = array.indexOf(value, i + 1)) !== -1) {
    indizes.push(i);
}

這將返回[1, 4] ,當然可以與擴展Array的原型相結合。

indexOf的第二個參數指定在給定數組中開始搜索的位置。

AFAIK,沒有Javascript或jQuery函數可以一步完成,你必須編寫一個循環。

var indexes = [];
$.each(abc, function(i, val) {
    if (val == "a") {
        indexes.push(i);
    }
}

這樣做:

var abc = ['a','a','b','a','c'];

for (var i=0; i<abc.length; i++) {if(abc[i]=='a') {console.log(i)};}

您可以利用$ .map()在您傳遞的函數返回undefined時不會在其結果數組中推送值的事實。

因此,你可以寫:

var abc = ["a", "a", "b", "a", "c"];
var indices = $.map(abc, function(element, index) {
    if (element == "a") {
        return index;
    }
});

你還在數組上使用reduce函數並將索引推送到累積數組,你需要從一個空數組開始,關於reduce的好處是它是異步的,並且時間執行比for循環更快,它也是數組上的本機函數,看下面,希望它有所幫助:

 var arr = [0, 1, 2, 3, 7, 2, 3, 4, 7, 8, 9, 2, 3];

            function indexesOf(num) {
                var reduced = arr.reduce(function(acc, val, ind, arr){
                  if(val === num){
                    acc.push(ind);
                  } 
                  return acc;
                }, []);
                return reduced;
            }

indexesOf(2); //[2, 5, 11]

演示用於循環

 var arr = ['a', 'a', 'b', 'a', 'c'];

var indexA = [];
for (var i = 0; i < arr.length; i++) {

    if ("a" == arr[i]) indexA.push(i)
}

如果您的數組大小是固定的,那么您可以使用indexOf()在數組中找到第一個匹配項。 使用找到的索引值作為indexOf()起始點來查找其他匹配項。

var firstOccurance = [your_array].indexOf(2)
var secondOccurance = [your_array].indexOf(2, firstOccurance + 1)

您可以使用Array#reduce with Array#concat檢查所需項目,獲取索引或空數組。

 var abc = ['a', 'a', 'b', 'a', 'c'], indices = abc.reduce((r, v, i) => r.concat(v === 'a' ? i : []), []); console.log(indices); 

ES5

 var abc = ['a', 'a', 'b', 'a', 'c'], indices = abc.reduce(function (r, v, i) { return r.concat(v === 'a' ? i : []); }, []); console.log(indices); 

使用ES6語法,您可以使用forEach和三元運算符:

const abc = ['a','a','b','a','c']
let matchingIndexes = []
abc.forEach( (currentItem, index) => {
     currentItem === 'a' ? matchingIndexes.push(index) : null
})
console.log(matchingIndexes) // [0, 1, 3]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM