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?

asked Jul 14, 2015 at 6:26

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]);
});
answered Jul 14, 2015 at 6:28
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]
});
answered Jul 14, 2015 at 6:32

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>

answered Jul 14, 2015 at 6:50

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]);
}
answered Jul 14, 2015 at 6:31

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']
answered Jul 14, 2015 at 6:49

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.