-2

If I have:

let a = [1,3,4,5];

how do I dynamically set b to have the same length as a with each entry containing "<", i.e.

Expected result:

b = ["<","<","<","<"];
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
Baz
  • 12,713
  • 38
  • 145
  • 268

2 Answers2

2

You can use Array#map:

const a = [1,3,4,5];

const b = a.map(() => "<");

console.log(b);

You can use Array#from:

const a = [1,3,4,5];

const b = Array.from(a, () => "<");

console.log(b);

Or you can use Array#fill:

const a = [1,3,4,5];

const b = new Array(a.length).fill("<");

console.log(b);
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
  • I think my solution is clearer, what do you think? I think your map solution is much better than the array solution. – Baz Nov 05 '17 at 15:05
  • Ah. I see you've add an Array#fill solution as well :) Array#fill is good when you want to duplicate primitives. If you'll use an array or an object, all array items would point to the same array/object. Array#from/#map in this case are doing the same thing. I think I would go with map as well. – Ori Drori Nov 05 '17 at 15:09
0

Here's a solution:

Array(a.length).fill('<');
Baz
  • 12,713
  • 38
  • 145
  • 268