简体   繁体   中英

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.

I got some code in StackOverflow but its checking only num 2 value, i need to check every element and return index value .

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/

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:

在此处输入图像描述

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:

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

DEMO

Copy this code and see on console.log

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

Sorry, here you can see: 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(', ') )
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM