A basic use case of Arguments or Rest Parameters
Hasib Muhammad

Hasib Muhammad @hasib

Location:
Dhaka, Bangladesh
Joined:
Apr 28, 2018

A basic use case of Arguments or Rest Parameters

Publish Date: Jul 19 '21
3 0

Seek and Destroy

You will be provided with an initial array (the first argument in the destroyer function), followed by one or more arguments. Remove all elements from the initial array that are of the same value as these arguments.

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].
destroyer([3, 5, 1, 2, 2], 2, 3, 5) should return [1].
destroyer([2, 3, 2, 3], 2, 3) should return [].

Approach:

  • Make an array with with the parameters except the 1st array
  • Filter the 1st array excluding the new array items

Using Arguments:

function destroyer(arr) {
    let newAr = [];
    for( let i = 1; i < arguments.length; i++ ) {
      newAr.push( arguments[i] );
    }
    return arr.filter( item => !newAr.includes(item) );
}
Enter fullscreen mode Exit fullscreen mode

Using Rest Parameters:

const destroyer = (...arr) => {
    const checkedArr = [...arr][0];

    let newAr = [];
    for( let i = 1; i < [...arr].length; i++ ) {
      newAr.push( [...arr][i] );
    }

    return checkedArr.filter( item => !newAr.includes(item) );
}
Enter fullscreen mode Exit fullscreen mode

Comments 0 total

    Add comment