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

时间:2016-05-04 19:25:35

标签: javascript arrays

现在我在这个数组值4中有一个数组var a = [4,7,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/

4 个答案:

答案 0 :(得分:0)

<强>答案

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

此代码背后的逻辑是检查每个值与其他值的数组,以便重复值&#39;索引可以找到。

答案 1 :(得分:0)

不明白你想要什么。下面的代码为您提供数据集中每个值的所有索引。

输出:

enter image description here

代码

ristoreApp.controller("loginCtrl", 
    ['$scope', '$location', 'loginFactory', 
    function($scope, $location, loginFactory){
        $scope.username = '';
        $scope.password = '';
        $scope.authenticate = function() {
            loginFactory.login($scope.username, $scope.password)
            .then(function(response) {
                loginFactory.setCredentials($scope.username, $scope.password);
                $location.path('/home');
            }, function errorCallBack(response) {
                console.log("Failed auth");
                $location.path('/login');
            });
        }
    }]);

答案 2 :(得分:0)

使用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]
}

DEMO

答案 3 :(得分:-1)

抱歉,您可以在此处看到: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(', ') )
}