N00b
N00b

Reputation: 149

Array "mapping"

If I have an array of items, for example:

var names = ['Rita', 'Sarah', 'Lisa', 'Joe', 'Ralph', 'Linda', 'Richard', 'Chris'];

And I have an array of numbers, for example:

var numbers = [2, 3, 5, 7];

How would I use these numbers to act as order numbers to get specific names?


What I mean by that?

Have a function that takes those two arrays and gives me an output:

output = ['Lisa', 'Joe', 'Linda', 'Chris'];

Does JavaScript have any specific functions for that or would I need to code something myself?

Upvotes: 3

Views: 72

Answers (1)

Pranav C Balan
Pranav C Balan

Reputation: 115222

Use map() for that

var names = ['Sarah', 'Lisa', 'Joe', 'Ralph', 'Linda', 'Richard', 'Chris'];
var numbers = [2, 3, 5, 7];

var res = numbers.map(function(v) {
  return names[v - 1]
})

// with ES6 arrow function
// var res = numbers.map(v => names[v - 1]);

document.write('<pre>' + JSON.stringify(res, null, 3) + '</pre>');


Or using filter()

var names = ['Sarah', 'Lisa', 'Joe', 'Ralph', 'Linda', 'Richard', 'Chris'];
var numbers = [2, 3, 5, 7];

var res = names.filter(function(v, i) {
  return numbers.indexOf(i + 1) > -1;
})

// with ES6 arrow function
// var res = numbers.filter((v, i) => numbers.indexOf(i + 1) > -1);

document.write('<pre>' + JSON.stringify(res, null, 3) + '</pre>');

Upvotes: 6

Related Questions