繁体   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