goodvibration
goodvibration

Reputation: 6206

How can I port this "one-line for loop" from Python to JavaScript?

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.

Upvotes: 4

Views: 1613

Answers (4)

Marlo
Marlo

Reputation: 504

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!

Upvotes: 0

Andy
Andy

Reputation: 63524

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.

Upvotes: 4

developer_hatch
developer_hatch

Reputation: 16224

you can use map in this case

function functionF(x){return x}

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

Upvotes: 3

Cruiser
Cruiser

Reputation: 1616

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;

Upvotes: 3

Related Questions