如何在javascript中获取相同数组值的索引值
现在我有一个数组如何在javascript中获取相同数组值的索引值,javascript,arrays,Javascript,Arrays,现在我有一个数组var a=[4,7,4]在这个数组中,值4是相同的值,我如何才能得到相同值的索引 我在StackOverflow中得到了一些代码,但它只检查num 2值,我需要检查每个元素并返回索引值 JS: var数据集=[2,2,4,2,6,4,7,8]; var结果=[]; 对于(i=0;i
var a=[4,7,4]
在这个数组中,值4是相同的值,我如何才能得到相同值的索引
我在StackOverflow中得到了一些代码,但它只检查num 2值,我需要检查每个元素并返回索引值
JS:
var数据集=[2,2,4,2,6,4,7,8];
var结果=[];
对于(i=0;i
对不起,您可以在这里看到:
回答
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);
var数据集=[2,2,4,2,6,4,7,8];
var结果=[];
对于(i=0;i for(j=i+1;j不一定能理解您想要什么。下面的代码为您提供了数据集中每个值的所有索引
输出:
密码
var数据集=[2,2,4,2,6,4,7,8];
var结果={};
对于(i=0;i console.log(结果);
使用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;
}, {});
输出
{
"2": [0, 1, 3],
"4": [2, 5],
"6": [4],
"7": [6],
"8": [7]
}
与其只学习你显然不懂的代码,不如试着学习一些javascript?这只是一个友好的建议。上一周我学习了javascript并尝试了,但我没有得到它。感谢broWhat,这是你希望从[2,2,4,2,6,4,7,8]
?@toraz..[2,3,2]获得的输出在这个数组中,2是一些重复的值,我需要输出索引值0,2
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;
}, {});
{
"2": [0, 1, 3],
"4": [2, 5],
"6": [4],
"7": [6],
"8": [7]
}