FCC--Seek and Destroy(摧毁数组)

来源:互联网 发布:网络错误651调制解调器 编辑:程序博客网 时间:2024/05/28 11:30

算法描述:实现一个摧毁(destroyer)函数,第一个参数是待摧毁的数组,其余的参数是待摧毁的值。

例子: destroyer([1, 2, 3, 1, 2, 3], 2, 3) 应该返回 [1, 1].

算法思路:1,将数组中的数字和后面的参数进行一一匹配,不相等则返回,相等则不返回。

实现方法:算法类似过滤因此可以使用filter函数,将数组中的数字过滤。

使用arguments来进行参数的遍历。

function destroyer(arr) {  // Remove all the values  var arr_arg = arguments;  for(var i = 1; i < arr_arg.length; i++){    arr = arr.filter(function(val){      return arr_arg[i] !== val;       });    }  return arr;}destroyer([1, 2, 3, 1, 2, 3], 2, 3);
用for循环将数组中的数字与参数进行匹配,除了第一个参数(为数组)。

以上是最基础的一种解法,一行就可以搞定。

利用reduce中的遍历省掉了for循环,具体方法如下。

function destroyer(arr) {  // Remove all the valuesreturn [].slice.call(arguments).reduce(function (prev, next) {        return prev.filter( e => e !== next);    });}destroyer([1, 2, 3, 1, 2, 3], 2, 3);

[ ].slice.call(arguments)的意思和arguments.slice()的方法一样,但是arguments没有这种方法,所以用call方法调用。

reduce()方法以pre为基准对后面的next进行遍历,利用filter进行过滤。

(e => e  !== next)为ES6方法同ES5方法:(fucntion(e){return e !== next})

需要熟练掌握call方法和reduce的遍历方法。



原创粉丝点击