Home > front end >  Grab first element from three arrays and put them inside its own array, then do the same for the sec
Grab first element from three arrays and put them inside its own array, then do the same for the sec

Time:04-22

I have three arrays

arr1 = ["a1", "a2", "a3"]

arr2 = ["b1", "b2", "b3"]

arr3 = ["c1", "c2", "c3"]

and I want three new arrays to look like so

arr4 = ["a1", "b1", "c1"]

arr5 = ["a2", "b2", "c2"]

arr6 = ["a3", "b3", "c3"]

How can I accomplish getting these new arrays in JavaScript?

CodePudding user response:

Here's one way - put the source arrays in one variable, use the length of the shortest source array as the iterator length and create the new variables on the fly.

let arr1 = ["a1", "a2", "a3"]
let arr2 = ["b1", "b2", "b3"]
let arr3 = ["c1", "c2", "c3"]

// just in case they're not all the same length, we'll use the shortest one as the iterator length

let ct = 0,
  st = 4,
  arrs = [arr1, arr2, arr3],
  len = Math.min(arr1.length, arr2.length, arr3.length);
while (ct < len) {
  this[`arr${st ct}`] = arrs.map(a => a[ct]);
  ct  ;
}

console.log(arr5)

CodePudding user response:

let mixedArr = [arr1, arr2, arr3];
let res = [];
for (i=0;i<mixedArr.length;i  ) {
    res.push(mixedArr.map(arr => arr[i]))
}
console.log(res)

And then you can just grab what you need from the finished array

CodePudding user response:

You Can use two loop to do that but you will add all arrays in one array to do the loop and we extract new arrays in another array

Here is your code

let arr1 = ["a1", "a2", "a3"],
arr2 = ["b1", "b2", "b3"],
arr3 = ["c1", "c2", "c3"];

We add all arrays in one variable

let allArr = [arr1, arr2, arr3];

We make a array to give all new arrays in

let resultArr = [];

We make the first loop to loop in each array

for (let i = 0; i < allArr.length; i  ) {

We make a array called res to make the new arrays

let res = [];

We make another loop on allArr Variable but for change we use a foreach loop

  allArr.forEach((arr) => {
    res.push(arr[i]);
  });

Then We add res after we make it to the resultArr Vairable

resultArr.push(res);

And We close out loop

}

Here is you code

let arr1 = ["a1", "a2", "a3"],
  arr2 = ["b1", "b2", "b3"],
  arr3 = ["c1", "c2", "c3"];

let allArr = [arr1, arr2, arr3];
let resultArr = [];
for (let i = 0; i < allArr.length; i  ) {
  let res = [];
  allArr.forEach((arr) => {
    res.push(arr[i]);
  });
  resultArr.push(res);
}

I add this loop to log the array in console only. To see that working live

resultArr.forEach((arr) => {
  console.log(arr);
});

let arr1 = ["a1", "a2", "a3"],
  arr2 = ["b1", "b2", "b3"],
  arr3 = ["c1", "c2", "c3"];

let allArr = [arr1, arr2, arr3];
let resultArr = [];
for (let i = 0; i < allArr.length; i  ) {
  let res = [];
  allArr.forEach((arr) => {
    res.push(arr[i]);
  });
  resultArr.push(res);
}
resultArr.forEach((arr) => {
  console.log(arr);
});

I hope to be good in my explain :)

CodePudding user response:

This may be one possible solution to achieve the desired objective.

Code Snippet

// method to transpose the arrays
const transpose = arr => {
  // first create a placeholder "result" 2D array
  const result = [
    ...Array(Math.min(
      ...arr.map(a => a.length)
    ))
  ].map((_, i) => [
    ...Array(arr[i].length)
  ].map(x => ""));
  
  // now, traverse through input 2D array & 
  // populate "result" by transposing row & col
  arr.forEach((row, rIdx) => 
    row.forEach((elt, cIdx) => 
      result[cIdx][rIdx] = elt
    )
  )
  
  return result;
};

const arrayOfArrays = [
  ["a1", "a2", "a3"],
  ["b1", "b2", "b3"],
  ["c1", "c2", "c3"]
];

console.log(
  'test case 1: ',
  JSON.stringify(arrayOfArrays),
  '\nresult: ',
  JSON.stringify(transpose(arrayOfArrays))
);

// using with the context of the question

const arr1 = ["a1", "a2", "a3"];
const arr2 = ["b1", "b2", "b3"];
const arr3 = ["c1", "c2", "c3"];

console.log(
  'using arr1, 2, 3: \n',
  JSON.stringify({arr1, arr2, arr3}),
  '\nraw-result: ',
  JSON.stringify(transpose([arr1, arr2, arr3]))
);

// getting the result arrays separately
const [arr4, arr5, arr6] = transpose([arr1, arr2, arr3]);

console.log(
  'showing result arrays arr4, 5, 6: \n',
  JSON.stringify({arr4, arr5, arr6})
);

// Testing with "20" element arrays

const alph = "abcdefghijklmnopqrstuvwxyz".split('');
const num = 20;
const twentyArr = [...Array(num).keys()].map(k => [...Array(num).keys()].map((_, i) => `${alph[k]}${i 1}`));

console.log(
  'Testing for twenty elements array: \n',
  JSON.stringify(twentyArr),
  '\nresult:\n',
  JSON.stringify(transpose(twentyArr))
);
.as-console-wrapper { max-height: 100% !important; top: 0 }

Explanation

Inline comments provided in the snippet above.

  • Related