4

I'm not sure about the terminology used (I think it's called "lambda" or something like that), so I cannot do a proper search.

The following line in Python:

 a, b, c, d, e = [SomeFunc(x) for x in arr]

How can I do the same in Javascript?

I have this to begin with:

let [a, b, c, d, e] = arr;

But I still need to call SomeFunc on every element in arr.

4

4 Answers 4

4

A close approximation would be to use the array method map. It uses a function to perform an operation on each array element, and returns a new array of the same length.

const add2 = (el) => el + 2;

const arr = [1, 2, 3, 4, 5];
let [a, b, c, d, e] = arr.map(add2);

console.log(a, b, c, d, e);

Be careful when you use array destructuring to ensure that you're destructuring the right number of elements for the returned array.

Sign up to request clarification or add additional context in comments.

2 Comments

I'd be careful with the destructuring just because you might unknowingly leave off elements of the array.
Thanks. I added a note to that effect to the answer.
3

It's called .map() in JavaScript and you'd use it like this:

let arr = [1,2,3,4].map(someFunc);

and someFunc would be defined somewhere else, maybe:

function someFunc(x){ return ++x };
//or es6
let someFunc = x => ++x;

Comments

3

you can use map in this case

function functionF(x){return x}

let [a, b, c, d, e] = arr.map(functionF);

Comments

0

The term you are looking for is lambda functions.

These types of functions are ideal for quick, one-time calculations. The javascript equivalent is the map() function. For your specific case, the syntax would be

    let arr = some_array.map(x => {
        return SomeFunc(x);
    });

For example, the statement

    let arr = [1, 2, 8].map(num => {
        return num * 2;
    });

will assign the list [2, 4, 16] to the variable arr.

Hope that helps!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.