简体   繁体   中英

Rearrange values in an Array of Arrays

I have this data:

var ArrdeArr = [[1,2,3],[5,6,3],[9,5,1]]
var letter  = [x,y,z]

And each array in the ArrdeArr belongs to the letter.

Expected Output:

[x,[1,5,9]];
[y,[2,6,5]];
[z,[3,3,1]];

If I don't make myself clear please let me know

You may try it like this:

 var ArrdeArr = [[1,2,3],[5,6,3],[9,5,1]]; var letter = ['x','y','z']; const result = letter.map((e, i) => [e, ArrdeArr.map(_e => _e[i])]); console.log(result);

The x , y , z doesn't exist in the context, so I replaced them with strings.

You can use Array.prototype.reduce() combined with Array.prototype.map() :

 const arrDeArr = [[1,2,3], [5,6,3], [9,5,1]] const letter = ['x', 'y', 'z'] const result = arrDeArr.reduce((a, c, i, arr) => [...a, [letter[i], arr.map(a => a[i])]], []) console.log(result)

Assuming both the arrays are of same length

var ArrdeArr = [[1,2,3],[5,6,3],[9,5,1]]
  var letter = ["x", "y", "z"];
  var finalArray = []
  letter.map((letter, index) => {
    var nestedArr = [letter]
    ArrdeArr.map(element => {
      nestedArr.push(element[index])
    })
    finalArray.push(nestedArr)
  })

  console.log(finalArray)

For some reason my brain wasn't working. Here's what I came up with:

 function transpose(array){ const r = array.map(()=>[]); array.forEach(a=>{ a.forEach((n, i)=>{ if(r[i])r[i].push(n); }); }); return r; } const trp = transpose([[1,2,3], [5,6,3], [9,5,1]]); console.log(trp); console.log({x:trp[0], y:trp[1], z:trp[2]});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM