Is there a shortcut to accessing elements of an array using an array of indices rather than going one index at a time?
Example (this doesn't work):
var array = ["One", "Two", "Three", "Four"];
var indices = [1, 3];
var result = array[indices];
where result would be ["Two", "Four"].
-
1you can extend array with a function that would have this functionalityComfortably Numb– Comfortably Numb2013年08月06日 18:13:59 +00:00Commented Aug 6, 2013 at 18:13
3 Answers 3
You can make one and have it available to all Arrays if you've no qualms about extending native prototypes in your environment.
Array.prototype.atIndices = function(ind) {
var result = [];
for (var i = 0; i < arguments.length; i++) {
if (arguments[i] in this)
result.push(this[arguments[i]])
}
return result;
}
var result = array.atIndices(1,3);
You could also have it check to see if an Array was passed, or a mix of indices and Arrays.
Array.prototype.atIndices = function(ind) {
var result = [];
for (var i = 0; i < arguments.length; i++) {
if (Array.isArray(arguments[i]))
result.push.apply(result, this.atIndices.apply(this, arguments[i]))
else if (arguments[i] in this)
result.push(this[arguments[i]])
}
return result;
}
This will actually flatten out all Arrays, so they could be as deeply nested as you want.
var result = array.atIndices(1, [3, [5]]);
6 Comments
Array.prototype and you probably shouldn't. Just makes the function signature to take the array as argument.array.atIndices(1) is not that much simpler than someNS.atIndices(array, 1).Array.prototype.atIndices function that behaves differently? That's just one of many cases that could lead to an unpredictable maintenance nightmare. Here's a good article by Nicholas C.Zakas that might change your mind nczonline.net/blog/2010/03/02/… Now there is:
function pluck(arr, indices) {
var result = [],
i = 0,
len = indices.length;
for (; i < len; i++) {
result.push(arr[indices[i]]);
}
return result;
}
Comments
As an alternative to rolling your own, if you have access to Lo-Dash (which you should totally use because it is awesome) its at function does exactly what you want.
Your usage would be:
var result = _.at(array, indices);