为了账号安全,请及时绑定邮箱和手机立即绑定

JS:查找在数组中出现 x 多次的元素。(没有对象)

JS:查找在数组中出现 x 多次的元素。(没有对象)

繁花如伊 2022-11-03 09:52:37
给定arr = [1,5,3,5,1,5,6,6,6];如果我想找到出现的元素,比如x = 3数组中的时间,我将如何在不使用对象的情况下做到这一点?即5,6。最好通过数组方法。
查看完整描述

3 回答

?
RISEBY

TA贡献1856条经验 获得超5个赞

您应该能够仅使用filter()indexOf()和来实现reduce()

function filterByCount(array, count) {

  return array.filter((a, index) =>

    array.indexOf(a) === index &&

    array.reduce((acc, b) => +(a === b) + acc, 0) === count

  );

}


const arr = [1, 5, 3, 5, 1, 5, 6, 6, 6];


console.log(filterByCount(arr, 3));


请注意,这种方法效率很低。通过使用类似的类Map,您可以在 O(n) 时间内而不是 O(n 2 ) 时间内实现这一目标。


在 O(n log(n)) 时间内实现此目的的另一种不太简单的方法是对数组进行排序,然后将每个值的第一个和最后一个索引之间的差异与预期的count. 此解决方案需要sort() 和filter()。如果您不想改变原始数组,那么slice()也需要:

function filterByCount(array, count) {

  // uncomment to avoid mutating the input array

  return array/*.slice()*/.sort((a, b) =>

    a - b

  ).filter((value, index, sorted) =>

    (index === 0 || sorted[index - 1] !== value) &&

    index + count - 1 < sorted.length &&

    sorted[index + count - 1] === value &&

    (index + count >= sorted.length || sorted[index + count] !== value)

  );

}


const arr = [1, 5, 3, 5, 1, 5, 6, 6, 6];


console.log(filterByCount(arr, 3));


查看完整回答
反对 回复 2022-11-03
?
肥皂起泡泡

TA贡献1829条经验 获得超6个赞

不过,这只是一个想法,如果您可以对数组进行排序,则可以计算连续出现的数字。


function findRepeatingNumbers(numbers, count) {

  numbers.sort((a, b) => a - b);


  const found = [];

  let counter = 1;


  for (let i = 1; i < numbers.length; i++) {

    if (numbers[i - 1] == numbers[i]) {

      counter += 1;

    } else {

      if (counter === count) {

        found.push(numbers[i - 1]);

      }

      counter = 1;

    }

  }


  if (counter == count) {

    found.push(numbers[numbers.length - 1]);

  }


  return found;

}


console.log(findRepeatingNumbers([1, 5, 3, 5, 1, 5, 6, 6, 6], 3));


查看完整回答
反对 回复 2022-11-03
?
慕莱坞森

TA贡献1810条经验 获得超4个赞

如果你想找出在数组中出现了多少次的元素,你可以很容易地知道下面这段代码。例如,这里的 6 是这个数组中的 3 次。


运行代码片段检查一下。


let arr = [1, 5, 3, 5, 1, 5, 6, 6, 6];

console.log((arr.join("").match(new RegExp("6", "g")) || []).length)


查看完整回答
反对 回复 2022-11-03
  • 3 回答
  • 0 关注
  • 95 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信