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
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]);
});
Comments
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
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
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
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']