[英]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;
回答
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);
此代码背后的逻辑是检查每个值与数组的其他值,以便可以找到重复值的索引。
使用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.