将相邻重复值分组为数组的最佳方法

时间:2018-08-01 13:13:02

标签: javascript loops lodash

我有一个数组r -> S,它的值类似于

roomList

我想做的是将所有let roomList=[ {value:1,type:2},{value:2,type:2},{value:3,type:2},{value:4,type:3}, {value:5,type:4},{value:6,type:4},{value:7,type:6},{value:8,type:6}, {value:9,type:1},{value:10,type:8},{value:11,type:8},{value:12,type:8} ]; 推入另一个数组(roomList [i] .value将是唯一的)。但是有些我无法获得所有想要的对象。

我的代码是这样

roomList[i].value

是否还有一种方法可以避免在let adjacentRoomId=[]; for(let i=0;i<roomList.length;i++){ for(let j=i+1;j<roomList.length;j++){ if(roomList[i].type===roomList[j].type){ adjacentRoomId.push(roomList[i].value); break; } } } 数组中重复。 我也在使用lodash

3 个答案:

答案 0 :(得分:1)

您可以按type分组。

let roomList = [{ value: 1, type: 2 }, { value: 2, type: 2 }, { value: 3, type: 2 }, { value: 4, type: 3 }, { value: 5, type: 4 }, { value: 6, type: 4 }, { value: 7, type: 6 }, { value: 8, type: 6 }, { value: 9, type: 1 }, { value: 10, type: 8 }, { value: 11, type: 8 }, { value: 12, type: 8 }],
    result = Array.from(roomList.reduce((m, o) => m.set(o.type, (m.get(o.type) || []).concat(o)), new Map).values());
    
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

let roomList = [{ value: 1, type: 2 }, { value: 2, type: 2 }, { value: 3, type: 2 }, { value: 4, type: 3 }, { value: 5, type: 4 }, { value: 6, type: 4 }, { value: 7, type: 6 }, { value: 8, type: 6 }, { value: 9, type: 1 }, { value: 10, type: 8 }, { value: 11, type: 8 }, { value: 12, type: 8 }],
    result = _(roomList)
        .groupBy('type')
        .map((values, type) => ({ type, values: _.map(values, 'value') }))
        .value();

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>

答案 1 :(得分:1)

您还可以使用ES6 Set来解决唯一的问题。然后它是缩小/查找组合,并且可以是单线:

let roomList=[
  {value:1,type:2},{value:2,type:2},{value:3,type:2},{value:4,type:3}, 
  {value:5,type:4},{value:6,type:4},{value:7,type:6},{value:8,type:6}, 
  {value:9,type:1},{value:10,type:8},{value:11,type:8},{value:12,type:8}
];

var result = _.reduce(roomList, (r,c,i,a) => 
_.find(a, x => x.type == c.type && x.value != c.value) ? r.add(c.value) : r, new Set)

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

答案 2 :(得分:0)

仅遍历主数组,然后检查要生成的第二个数组中的元素。

如果元素存在于第二个数组中,请不要将其插入第二个数组中。

在输出中,{value:12,type:8},{value:9,type:1}将不会重复,只会出现一次。

var x = roomList=[
  {value:1,type:2},{value:2,type:2},{value:3,type:2},{value:4,type:3}, 
  {value:5,type:4},{value:6,type:4},{value:7,type:6},{value:8,type:6}, 
  {value:9,type:1},{value:10,type:8},{value:11,type:8},{value:12,type:8},{value:12,type:8},{value:9,type:1}
];

var n = [];

x.forEach(function(e){
  var isExists = false; 
	n.forEach(function(ne){
		if(ne == e.value){
			isExists = true;
		}
	});
	if(!isExists){
		n.push(e.value);
	}
});

console.log(n.join(","));

console.log(n);