简体   繁体   English

如何在 javascript 中获取相同数组值的索引值

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

Now i have an array var a = [4,7,4] in this array value 4 is same values and how can i get the index of same value.现在我有一个数组var a = [4,7,4]在这个数组值 4 是相同的值,我怎样才能获得相同值的索引。

I got some code in StackOverflow but its checking only num 2 value, i need to check every element and return index value .我在 StackOverflow 中有一些代码,但它只检查 num 2 值,我需要检查每个元素并返回索引值

JS: 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 JSFIDDLE

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

Answer回答

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);

The logic behind this code is check every value with other values of array so that duplicate values' index can be found.此代码背后的逻辑是检查每个值与数组的其他值,以便可以找到重复值的索引。

Not sur to understand what you want.不知道你想要什么。 The code bellow give you all index per value in the dataset.下面的代码为您提供数据集中每个值的所有索引。

Output: Output:

在此处输入图像描述

Code代码

 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);

Use reduce to build a lookup:使用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 OUTPUT

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

DEMO演示

Copy this code and see on console.log复制此代码并在 console.log 上查看

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

Sorry, here you can see: http://jsfiddle.net/42y08384/18/对不起,在这里你可以看到: 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