Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map through a rest parameter?

Tags:

javascript

I am attempting to map through a rest parameter.

MDN says: The rest parameter syntax allows us to represent an indefinite number of arguments as an array.

So if ...numbers is an array, when I use map on it ie numbers.map(), the array it's mapping is [33,44,55]. How can I now map each element of the ...numbers array? I can't enter numbers.map(numbers.slice(numbers.length - 1)) because each numbers is the total array.

TLDR; I guess to put it simply, how can I map each element of the rest parameter?

I'm out of ideas.

function checkLastDigit(num1, num2, num3) {
    function collectDigits(...numbers) {
        let digitsArr = [];
        digitsArr = numbers.map(collectLastDigit());
        return digitsArr;
    }

    function collectLastDigit() {
        return this.slice(this.length - 1)
    }

    return collectDigits(num1, num2, num3);
}
checkLastDigit(33, 44, 55);
like image 536
kevin Avatar asked Jan 25 '19 01:01

kevin


1 Answers

It's just an array, so you can iterate through it just the way you would iterate through any array.

A couple problems with your current code: don't invoke the callback function while paassing it to .map, instead just pass the function:

digitsArr = numbers.map(collectLastDigit);

Also, numbers do not have a slice method , so this.slice won't work - if you want to slice, coerce to a string first. You may also use slice(-1) rather than passing the length - 1. Also, this won't refer to the item being iterated over - instead, use the first parameter of the callback instead:

function checkLastDigit(num1, num2, num3) {
    const collectLastDigit = num => String(num).slice(-1);
    const collectDigits = (...numbers) => numbers.map(collectLastDigit);

    return collectDigits(num1, num2, num3);
}
console.log(checkLastDigit(33, 44, 55));

If you want an array of numbers as a result rather than an array of strings, then change collectLastDigit to coerce back to a number:

const collectLastDigit = num => Number(String(num).slice(-1));

You could also use rest parameters in checkLastDigit too, if you wanted, rather than requiring exactly 3 arguments:

function checkLastDigit(...nums) {
    const collectLastDigit = num => String(num).slice(-1);
    const collectDigits = (...numbers) => numbers.map(collectLastDigit);

    return collectDigits.apply(undefined, nums);
}
console.log(checkLastDigit(33, 44, 55));
like image 96
CertainPerformance Avatar answered Oct 29 '22 18:10

CertainPerformance