0

What I need is to get specific items (defined by array if indices) from an array. Let say I have this source array [2,4,1,6,8] and this array of indices [0,3] and I want the result to be [2,6]. So far I am doing this to achieve the result

var iter = -1;
source.filter(function(item) {iter++; if (indices.indexOf(iter)>-1) {return item}})

Is there any more elegant solution (maybe some javascript syntactic sugar I am not aware of) than this?

5 Answers 5

4

There is no syntactic sugar for this particular task, but a simpler way would be:

var destination = [];
indices.forEach(function(index) {
    destination.push(source[index]);
});
Sign up to request clarification or add additional context in comments.

Comments

3

You can use map:

var source = [2, 4, 1, 6, 8];
var indices = [0, 3];

var output = indices.map(function(i){
    return source[i]
});

Comments

2

It's probably best to check if the original array has the index before trying to access it.

var original = [1,2,3,4,5,6,7,8,9,10];
var indicesSafe = [2,6];
var indicesUnsafe = [2,1234];

function filter(original, indices) {
  var result = [];
  for (var i = 0; i < indices.length; i++) {
    var index = indices[i];
    
    // Check if index exists
    if (original.length > index) {
      
      // If so push onto return value
      result.push(original[index]);
    }
  }
  return result;
}

// Safe
var resultSafe = filter(original, indicesSafe);
// Unsafe
var resultUnsafe = filter(original, indicesUnsafe);

document.getElementById('output').innerHTML += JSON.stringify(resultSafe);
document.getElementById('output').innerHTML += "\n" + JSON.stringify(resultUnsafe);
<pre id="output"></pre>

Comments

0

This is what I would do:

var dataArray = [2,4,1,6,8];
var indicesArray = [0,3];
var resultArray = [];

for (var i=0; i<indicesArray.length; i++) {
    resultArray.push(dataArray[i]);
}

Comments

0

If you're considering a library you can use lodash _.at

_.at(['a', 'b', 'c'], [0, 2]);
// → ['a', 'c']

_.at(['barney', 'fred', 'pebbles'], 0, 2);
// → ['barney', 'pebbles']

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.