2

I have two arrays, one of data and one of indices:

var data = [
    'h', 'e', 'l', 'l', 'o', ' '
];
var indices = [
    4, 0, 5, 0, 1, 2, 2
];

I would like to create a third array, using cells of data in order indicated in indices, so it here it would be:

['o', 'h', ' ', 'h', 'e', 'l', 'l']

I know I could easily do it with a simple loop:

var newArray = new Array(indices.length);
for (var i in indices) {
    var index = indices[i];
    newArray.push(data[index]);
}

But I wonder if there is a cleaner/simpler way to do it, like an array method or a special constructor ?

3 Answers 3

5

You can use .map, like so

var data = [
    'h', 'e', 'l', 'l', 'o', ' '
];

var indices = [
    4, 0, 5, 0, 1, 2, 2
];

var res = indices.map(function (el) {
  return data[el];
});

console.log(res);

The map() method creates a new array with the results of calling a provided function on every element in this array.

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

Comments

2

You can also use map

var newArray = indices.map(function(i){
    return data[i]
});

Comments

0

You could have used while loop:

var data = [
  'h', 'e', 'l', 'l', 'o', ' '
];
var indices = [
  4, 0, 5, 0, 1, 2, 2
];
var l = indices.length,
  newArray = [];
while (l--)
  newArray[l] = data[indices[l]];
console.log(newArray);

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.