javascript - 重复时如何从数组中删除 *some* 项? (首选 Lodash/Underscore)

标签 javascript node.js underscore.js lodash

我正在尝试编写一个函数,从 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/

相关文章:

javascript - Angular HTTP 'get' 请求 304 错误

javascript - 单击按钮时显示数据库中的 WordPress 数据库自定义表行列值

javascript - 编写 Promise 时的错误模式?

node.js - nodemon 在 Windows 10 中不起作用

backbone.js - 为什么在backbone.js View 中使用bindAll?

javascript - 使用 connect 在 Gulp 中创建动态服务器

javascript - ReactJs:无法使用 map 循环对象数组

windows - 如何在 Windows 中使用某些预定义端口从 cmd 运行 node.js 应用程序

javascript - 循环对象以获取索引值

underscore.js - lodash/underscore 中的indexBy 相反?