1

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.

0

4 Answers 4

7

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)

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

3 Comments

Oh my, i never thought of going down this route! Thank you so much!
Amazing...so quick :P
@kdweber89 : glad to help :)
1

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

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

Cheers, Karol

Comments

1

How about :

var newArray = [];

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

console.log(newArray);

Comments

0

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);

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.