kdweber89
kdweber89

Reputation: 2174

javascript, looping through a multi-array to list the first element of the array

So I feel like I should be able to figure this one out, but for whatever reason, i've having some difficulty with it this morning.

I have an array with multiple arrays inside, and i want to loop through this big array and only list the first element in the smaller arrays.

so my array looks something like this

var array = [
             [1, 2],
             [1, 3],
             [3, 4]
            ]

So, essentially I want to be able to list, (1, 1, 3). The problem for me is that when i try to approach any for loop, i am able to separate the arrays, but not able to list the first element in each smaller array.

I know this is pretty elementary, and even though i did take a look and did not find much, i do feel like this question has already been asked.

Any help with this would be wonderful.

Much thanks.

Upvotes: 1

Views: 554

Answers (4)

Sherali Turdiyev
Sherali Turdiyev

Reputation: 1743

Just use for(...) instead of others for big array. It is fastest. You can see their speed difference in http://jsperf.com/find-first-from-multiple-arrray

enter image description here

var array = [
    [1, 2],
    [1, 3],
    [3, 4]
], r = [];

for (var i = 0; i < array.length; i++) {
    r.push(array[i][0]);
}
console.log(r);

Upvotes: 0

Pranav C Balan
Pranav C Balan

Reputation: 115222

You can use map() for creating a modified array

var array = [
  [1, 2],
  [1, 3],
  [3, 4]
];

var res = array.map(function(v) {
  return v[0];
});

alert(res)

Upvotes: 7

Anugerah Erlaut
Anugerah Erlaut

Reputation: 1120

How about :

var newArray = [];

array.forEach(function(el) {
   newArray.push(el[0]);
});

console.log(newArray);

Upvotes: 1

andrusieczko
andrusieczko

Reputation: 2824

If you just want to list [1,1,3], then this might be enough:

array.map(function(item) { return item[0]; });

Cheers, Karol

Upvotes: 1

Related Questions