9

Is there a one-line code to get an subarray from an array by index?

For example, suppose I want to get ["a","c","e"] from ["a","b","c","d","e"] by [0,2,4]. How to do this with a one-line code? Something like ["a","b","c","d","e"][0,2,4]..

0

4 Answers 4

24

You could use map;

var array1 = ["a","b","c"];
var array2 = [0,2];
var array3 = array2.map(i => array1[i]);
console.log(array3);

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

2 Comments

I actually like this better than my answer. Probably faster as well.
Is there a way so you don't have to traverse the array? Like a direct extraction from indexes or something like that?
6

You can use filter

const arr = ['a', 'b', 'c'];
const indexes = [0, 2];

const result = arr.filter((elt, i) => indexes.indexOf(i) > -1);

document.body.innerHTML = result;

6 Comments

What do you mean ?
@NinaScholz OP doesn't ask for this
const indexes = [2, 2]; try this @klugjo
@MuhammetCanTONBUL: That's pretty silly input considering what the OP is trying to do.
It does work, it returns ['c'], which is what we want I am guessing. Question doesn't say
|
5

You can use a combination of Array#filter and Array#includes

const array = ['a','b','c'];
console.log(array.filter((x,i) => [0,2].includes(i)));

4 Comments

Nice and simple. Although I'd have used a variable for the indexes array.
@Cerbrus I first wrote it with a variable but then I thought it was more visual to have it inline
Fair enough :-) Either way, +1
@Cerbrus Thanks for your comment ! Always nice to receive compliment :-D
4

You can use Array.prototype.reduce()

const arr = ['a', 'b', 'c', 'd', 'e'];
const indexes = [0, 2, 4];

const result = indexes.reduce((a, b)=> {
a.push(arr[b]);
return a;
}, []);

console.log(result);

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.