2017-02-04 62 views
1

我想從初始數組中刪除與這些參數具有相同值的所有元素。JavaScript將參數傳遞給過濾函數?

例:

destroyer([1, 2, 3, 1, 2, 3], 2, 3) should return [1, 1]. 
destroyer([1, 2, 3, 5, 1, 2, 3], 2, 3) should return [1, 5, 1]. 

這裏是我的代碼:

function takeaway(value) { 

    return ?? 
} 


function destroyer(arr) { 
    // Remove all the values\ 
    var args = Array.from(arguments); // args = [[1,2,3,1,2,3],2,3] 

    var arr1 = args.shift();   // arr1 = [1, 2, 3, 1, 2, 3] 
             // args = [2,3] 

    var filtered = arr1.filter(takeaway); 


    return filtered; 

} 

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

如果我沒有記錯我需要傳遞,我要拿出(在args陣列)進入過濾器的元素函數,所以它知道要過濾掉什麼......我將如何實現這一目標?

回答

2
const destroyer = (arr, ...nopes) => 
    arr.filter(value => !nopes.includes(value)) 

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

因爲這是很難理解的類型簽名,我會迴避有利於明確陣列像這樣的使用可變參數的功能,雖然路程。改變參數順序對於部分應用或者咖啡也會更好。

//: (Array Int, Array Int) -> Array Int 
const destroyer = (nopes, arr) => 
    arr.filter(value => !nopes.includes(value)) 

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

嘗試數組的包含函數。如果arr1元素不包含在args數組中,它將返回false,並且只有返回true的元素被濾除。

function destroyer(arr) { 
    // Remove all the values\ 
    var args = Array.from(arguments); // args = [[1,2,3,1,2,3],2,3] 

    var arr1 = args.shift();   // arr1 = [1, 2, 3, 1, 2, 3] 
             // args = [2,3] 

    var filtered = arr1.filter(function(value){ 
    return !args.includes(value); 
}); 


    return filtered; 

} 

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

使用Array#indexOf檢查,如果在參數

const destroyer = (arr, ...args) => arr.filter(value => args.indexOf(value) === -1); 
destroyer([1, 2, 3, 1, 2, 3], 2, 3); 
destroyer([1, 2, 3, 5, 1, 2, 3], 2, 3); 
0

存在的元素這是我與一些解釋解決方案。它與其他細微差別的其他類似。它更詳細地顯示了回調函數的功能。希望它能幫助大家理解它!

let arr = [1, 2, 3, 3, 4, 5] 

    function destroyer(myArray) { 
     let argsArr = Array.from(arguments)    //argsArr = [[1,2,3,3,4,5],3,4] 
     let sliced = argsArr.slice.call(arguments, 1) //sliced = [3,4] 
                 //myArray = [1,2,3,3,4,5] 
     function takeAway(val) {      // val = each element in myArray:1,2,3,3,4,5 
      return sliced.indexOf(val) === -1   //[3,4] indexOf 3,4 = true (+1) [3,4] indexOf 1,2,5 
                 // == false (-1) so it is returned by the filter method 
     } 
     let answer = myArray.filter(takeAway)   // answer = [1,2,5] 
     return answer 
    } 

    console.log(destroyer(arr, 3, 4))