Daniel Santos
Daniel Santos

Reputation: 15848

get duplicate values index using lodash

Say I have an array like this: ["a", "a", "b", "c", "c", "a"]

I need to know which value is duplicated in what index.

In this case that indexes 0, 1 and 5 has the "a" value duplicated and indexes 3 and 4 has the "c" value duplicated.

Upvotes: 1

Views: 1068

Answers (4)

Akrion
Akrion

Reputation: 18525

Here is an approach of ES6 and lodash. We use the .pickBy and .set from lodash and ES6 for the rest:

const data = ["a", "a", "b", "c", "c", "a"]

const result = _.pickBy(data.reduce((r,c,i,a) => a.indexOf(c, i) >= 0 ? _.set(r, c, [...r[c] || [], i]) && r : r, {}), x => x.length > 1)

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

The idea is to reduce and create an object with all properties having an array as value which indicates the indexes found. Then simply pick those props which their value length is bigger than 1.

Upvotes: 1

Pearman
Pearman

Reputation: 1068

Using Lodash:

import * as _ from "lodash";

let arr = ["a", "a", "b", "c", "c", "a"];

let result = _.omitBy(
  _.reduce(arr, (a, v, i) => _.set(a, v, (a[v] || []).concat([i])), {} ),
  v => v.length <= 1
);

console.log(result); // ​​​​​{ a: [ 0, 1, 5 ], c: [ 3, 4 ] }​​​​​

Upvotes: 1

Adrian
Adrian

Reputation: 8597

In plain Javascript you can do something like this:

var arr = ["a", "a", "b", "c", "c", "a"];
var sort = [];

for(var i = 0; i < arr.length; i++){
	
  var index = sort.find(function(x){
  	return x.Key == arr[i];
  });
  
  	
  if(index != undefined && index.Indexes != undefined){
     sort.find(function(x){
    	if(x.Key == arr[i]){
      	   x.Indexes.push(i);
        }
     })
  }else{
     sort.push({ Key: arr[i], Indexes: [i] });
  }

}

console.log(sort);


And if you want to wrap it into a function that accepts a single char and and retrieves the indexes for the specific char:

var arr = ["a", "a", "b", "c", "c", "a"];

Array.prototype.GetAllIndexesFor = function(char){
	  
var sort = [];
var arr = this;

  for(var i = 0; i < arr.length; i++){

    if(arr[i] == char){
      sort.push(i);
    }

  }
return sort;
}

var indexesForA = arr.GetAllIndexesFor('a');
var indexesForB = arr.GetAllIndexesFor('b');
var indexesForC = arr.GetAllIndexesFor('c');

console.log(indexesForA)
console.log(indexesForB)
console.log(indexesForC)

Upvotes: 0

Илья Зелень
Илья Зелень

Reputation: 8098

I realized what you need:

let arr = ["a", "a", "b", "c", "c", "a"]
let o = {}

arr.forEach((e, i) => {
  // if you need only duplicates
  if (arr.indexOf(e) - arr.lastIndexOf(e) === 0)
    return
    
  (o[e] = o[e] || []).push(i)
})

console.log(o)

Upvotes: -1

Related Questions