Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript: get subarray from an array by indexes

Tags:

javascript

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]..

like image 696
WCMC Avatar asked Jan 04 '18 07:01

WCMC


4 Answers

You could use map;

var array1 = ["a","b","c"];
var array2 = [0,2];
var array3 = array2.map(i => array1[i]);
console.log(array3);
like image 161
lucky Avatar answered Nov 05 '22 08:11

lucky


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;
like image 37
klugjo Avatar answered Nov 05 '22 08:11

klugjo


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)));
like image 41
Weedoze Avatar answered Nov 05 '22 09:11

Weedoze


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);
like image 26
marvel308 Avatar answered Nov 05 '22 08:11

marvel308