-1

I have the following array set:

myArr = [
   [red, 1],
   [blue, 2],
   [yellow, 3],
   [geen, 4]
];

Is there an operator/method in which I can return an array of just the 0 index item? So end result would be:

myArr2 = [red, blue, yellow, green]
Kode_12
  • 4,506
  • 11
  • 47
  • 97
  • Do you mean `['red', 1]`, or is `red` a ref to another var/object? – Andy Apr 25 '16 at 14:58
  • Same as in [From an array of objects, extract value of a property as array](http://stackoverflow.com/q/19590865/218196) – Felix Kling Apr 25 '16 at 14:58
  • You have to use `Array.prototype.reduce` for this task. Just do this one liner `myArr2 = myArr.reduce((p,c) => {p.push(c[0]); return p}, []);` – Redu Apr 25 '16 at 15:14

3 Answers3

2

You could use Array#map().

ES6

var myArr = [
   ['red', 1],
   ['blue', 2],
   ['yellow', 3],
   ['geen', 4]
];

document.write(myArr.map(a => a[0]));

ES5

var myArr = [
   ['red', 1],
   ['blue', 2],
   ['yellow', 3],
   ['geen', 4]
];

document.write(myArr.map(function (a) { return a[0]; }));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
2

Working Example using map:

var a  = [
   ["red", 1],
   ["blue", 2],
   ["yellow", 3],
   ["geen", 4]
];

var b = a.map(function(el) {
  return el[0];
});
omarjmh
  • 13,632
  • 6
  • 34
  • 42
0

you can do it like that

for(var i=0;i<myArr.length;i++){
    myArr2.push(myArr[i][0]);
}
console.log(myArr2); /// prints red, blue, yellow, green
Özgür Ersil
  • 6,909
  • 3
  • 19
  • 29