JavaScript算法笔记,数组过滤中可以使用计数器

题目:

使用参数过滤一个数组


destroyer([1, 2, 3, 1, 2, 3], 2, 3) should return [1, 1].
Passed
destroyer([1, 2, 3, 5, 1, 2, 3], 2, 3) should return [1, 5, 1].
Passed
destroyer([3, 5, 1, 2, 2], 2, 3, 5) should return [1].
Passed
destroyer([2, 3, 2, 3], 2, 3) should return [].
Passed
destroyer(["tree", "hamburger", 53], "tree", 53) should return ["hamburger"].
Passed
destroyer(["possum", "trollo", 12, "safari", "hotdog", 92, 65, "grandma", "bugati", "trojan", "yacht"], "yacht", "possum", "trollo", "safari", "hotdog", "grandma", "bugati", "trojan") should return [12,92,65]

代码如下


function destroyer(arr) {
  // Remove all the values
  let newArr = [];
  for (let i = 0; i < arr.length; i++)
  {
    var count = 0;//这个计数器帮助实现过滤
    for (let j = 0; j < arguments.length; j++)
    {
      if (arr[i] === arguments[j])
      {
        count++;
      }
    }
    if (count === 0)
    {
      newArr.push(arr[i]);
    }
  }
  return newArr;
}

destroyer([1, 2, 3, 1, 2, 3], 2, 3);

你可能感兴趣的:(JavaScript算法笔记,数组过滤中可以使用计数器)