-3

Let suppose I have an array like this

Let data = [ [bob,male,90,pass][sam,male,70,pass][grace,female,75,pass][harry,male,20,fail] ]

and I want to extract all the names and store them in a seperate array then how can I do it ? Means output should be like

[bob,sam,grace,harry]

2 Answers2

0

1) You can use map here with destructuring

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) Using map with index

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);
DecPK
  • 24,537
  • 6
  • 26
  • 42
0

Using for loops and 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);