Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I made new array from firsts elements of arrays from an array

How can I made new array from firsts elements of arrays from this array ?

[["1",2],["3",2],["6",2]] 

and I want it to be

['1', '3', '6'] 

My attempt:

var newArray = []

for (i = 0; i < arrayToCompare.length - 1; i++) {
    newArray.push(arrayToCompare[[0]])
}
like image 536
Rafał Avatar asked Dec 05 '19 09:12

Rafał


3 Answers

You could just use a simple map and destructure the first element:

const arr = [["1", 2],["3", 2],["6", 2]]
console.log(arr.map(([e]) => e))

The ([e]) part of that before the => is destructuring the parameter using array destructuring. It means that for each subarray passed to the map callback, e receives the value of the first element of the subarray. In ES5 and earlier, the ([e]) => e arrow function would be function(entry) { return entry[0]; }

Still, if you still don't understand the concept, prefer efficiency, or just want to go back to basics, you could use the trusty for loop, making sure to push only the first element of each subarray:

const arr = [["1", 2],["3", 2],["6", 2]]

const output = []
for (let i = 0; i < arr.length; i++) {
  output.push(arr[i][0])
}

console.log(output)
like image 150
Kobe Avatar answered Oct 21 '22 16:10

Kobe


Try this:

let arr = [["1", 2], ["3", 2], ["6", 2]];
let res = arr.map(val => {
    return val[0]
})
console.log(res);
like image 32
Saurabh Agrawal Avatar answered Oct 21 '22 15:10

Saurabh Agrawal


You can use Array.prototype.map() to crate a new array with the item from the first index:

var arr = [["1",2],["3",2],["6",2]]
var newArray = arr.map(i => i[0]);
console.log(newArray);
like image 42
Mamun Avatar answered Oct 21 '22 14:10

Mamun