Reputation: 2174
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
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
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
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
Reputation: 1120
How about :
var newArray = [];
array.forEach(function(el) {
newArray.push(el[0]);
});
console.log(newArray);
Upvotes: 1
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