使用lodash获取重复值索引

时间:2018-08-22 15:29:37

标签: javascript lodash

说我有一个像这样的数组:["a", "a", "b", "c", "c", "a"]

我需要知道哪个值在哪个索引中重复。

在这种情况下,索引0、1和5具有重复的“ a”值,而索引3和4具有重复的“ c”值。

4 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

这是ES6和lodash的一种方法。其余部分,我们使用lodash和ES6中的.pickBy .set

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>

这个想法是要减少和创建一个对象,该对象的所有属性都具有一个数组作为值,该数组指示找到的索引。然后只需选择其值长度大于1的道具即可。

答案 2 :(得分:0)

在纯Javascript中,您可以执行以下操作:

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


如果要将其包装到一个函数中,该函数接受单个char并检索特定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)

答案 3 :(得分:-1)

我意识到您的需求:

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)