我正在尝试编写一个函数,从 6 个骰子的数组中过滤掉三元组。有使用 Lodash 或 Underscore 的简单方法吗?
noTriplets([1,1,1,3,3,5]) // = [3,3,5]
noTriplets([1,1,1,1,3,5]) // = [1,3,5]
noTriplets([1,1,1,1,1,5]) // = [1,1,5]
noTriplets([1,1,1,5,5,5]) // = []
noTriplets([1,1,1,1,1,1]) // = []
最佳答案
有点粗糙和肮脏,但它不需要你提前知道你的三胞胎。在 noTriplets()
中——我创建了一个快速的 hashMap,然后遍历该对象。循环逻辑处理三元组。
const arrayTestOne = [1,1,1,3,3,5];
const arrayTestTwo = [1,1,1,1,3,3,5];
const arrayTestThree = [1,1,1,3,3,3];
const arrayTestFour = [1,1,1,1,3,3,3,5,5,5,5,5,5,5,5,5,5,5,5,7,7];
const hashMap = (array) => array.reduce((allNums, num) => {
if (num in allNums) {
allNums[num]++
}
else {
allNums[num] = 1
}
return allNums
}, {})
function noTriplets(arr) {
let newArr = [];
let obj = hashMap(arr);
for (var key in obj) {
for (let i=0; i < obj[key] % 3; i++) {
newArr.push(key)
}
}
console.log(newArr)
}
noTriplets(arrayTestOne)
noTriplets(arrayTestTwo)
noTriplets(arrayTestThree)
noTriplets(arrayTestFour)
关于javascript - 重复时如何从数组中删除 *some* 项? (首选 Lodash/Underscore),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45704834/