Supongamos que tengo una matriz como esta
Let data = [ [bob,male,90,pass][sam,male,70,pass][grace,female,75,pass][harry,male,20,fail] ]y quiero extraer todos los nombres y almacenarlos en una matriz separada, ¿cómo puedo hacerlo? Significa que la salida debería ser como
[bob,sam,grace,harry]
1) Puede usar el mapa aquí con desestructuración
let data = [ ["bob", "male", 90, "pass"], ["sam", "male", 70, "pass"], ["grace", "female", 75, "pass"], ["harry", "male", 20, "fail"], ]; const result = data.map(([name]) => name); console.log(result);2) Usar mapa con índice
let data = [ ["bob", "male", 90, "pass"], ["sam", "male", 70, "pass"], ["grace", "female", 75, "pass"], ["harry", "male", 20, "fail"], ]; const result = data.map((arr) => arr[0]); console.log(result);Uso de bucles for y switch:
// data array let data = [ ['bob','male',90,true], ['sam','male',70,true], ['grace','female',75,true], ['harry','male',20,false] ]; // instantiate sorted arrays let names = []; let gender = []; let age = []; let pass = []; // iterate on the array containing arrays for (let x = 0; x < data.length; x++) { // iterate inside the arrays for (let y = 0; y < data[x].length; y++) { // curData store the data we just now are looking at // while iterating through all the data curData = data[x][y]; // depending on y, save the data to the correct array switch (y) { case 0: names.push(curData); break; case 1: gender.push(curData); break; case 2: age.push(curData); break; case 3: pass.push(curData); break; } } } // print them out console.log(names); console.log(gender); console.log(age); console.log(pass);