簡體   English   中英

如何在 javascript 中獲取相同數組值的索引值

[英]How to get index value of same array value in javascript

現在我有一個數組var a = [4,7,4]在這個數組值 4 是相同的值,我怎樣才能獲得相同值的索引。

我在 StackOverflow 中有一些代碼,但它只檢查 num 2 值,我需要檢查每個元素並返回索引值

JS:

var dataset = [2,2,4,2,6,4,7,8];
var results = [];
for ( i=0; i < dataset.length; i++ ){
    if ( dataset[i] == 2 ){
        results.push( i );
    }
}

return results;

JSFIDDLE

http://jsfiddle.net/friendz/42y08384/15/

回答

var dataset = [2,2,4,2,6,4,7,8];
var results = [];
for ( i=0; i < dataset.length; i++ ){
    for(j=i+1;j<dataset.length;j++){
    if ( dataset[i] == dataset[j] ){
        results.push( j );
        break;
    } 
    }
}

console.log(results);

此代碼背后的邏輯是檢查每個值與數組的其他值,以便可以找到重復值的索引。

不知道你想要什么。 下面的代碼為您提供數據集中每個值的所有索引。

Output:

在此處輸入圖像描述

代碼

 var dataset = [2,2,4,2,6,4,7,8]; var results = {}; for ( i=0; i < dataset.length; i++ ) { if (typeof results[dataset[i]] === 'undefined') { results[dataset[i]] = []; } results[dataset[i]].push(i); } console.log(results);

使用reduce構建查找:

const out = dataset.reduce((p, c, i) => {

  // if the current value doesn't exist as a
  // key in the object, add it and assign it an
  // empty array
  p[c] = (p[c] || []);

  // push the index of the current element to its
  // associated key array
  p[c].push(i);
  return p;
}, {});

OUTPUT

{
  "2": [0, 1, 3],
  "4": [2, 5],
  "6": [4],
  "7": [6],
  "8": [7]
}

演示

復制此代碼並在 console.log 上查看

 console.log(Array.from({length: 50}, (v,i) => i));

對不起,在這里你可以看到: http://jsfiddle.net/42y08384/18/

var dataset = [2,2,4,2,6,4,7,8];
var results = {};
dataset.forEach(function(item, key) {
    if(!results[item]) {
    results[item] = [];
  }


  console.log(key)  
  results[item].push(key);
});

//results is an object where the key is the value from the dataset and the array within is the indexes where you can find them
for(key in results) {
    console.log('Value ' + key + ' can be found in position '+ results[key].join(', ') )
}

暫無
暫無

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

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