Sam Houston
Sam Houston

Reputation: 3651

Equivalent function without using a for loop in Javascript?

What would be the equivalent of this without using a for loop?

Unsure what array method to use

function func(x){
    var y = [];
    for(i=0;i<x.length;i++){
        y.push(x[i]);
        y.push(x[i]);
    }
    return y;
}

var input = [1,2,3,4,5,6];

console.log(func(input));// returns [1,1,2,2,3,3,4,4,5,5,6,6]

Upvotes: 2

Views: 83

Answers (2)

Davin Tryon
Davin Tryon

Reputation: 67296

You cannot map directly, but you could reduce into a new expanded array:

arr.reduce((prev, curr) => prev.concat([curr, curr]), []);

And this is without ES6 arrow function:

arr.reduce(function(prev, curr) { return prev.concat([curr, curr]); }, []);

Upvotes: 4

Armand
Armand

Reputation: 24333

There's no one-to-one mapping between your two lists. However, you could achieve the same with underscore e.g.:

_.flatten(_.map(input, function(item) {
  return [item, item];
}));

or

_.chain(input)
  .map(function(item) {
    return [item, item];
  })
  .flatten()
  .value();

Upvotes: 2

Related Questions