Home > Software engineering >  I am trying to regroup an array of arrays using reduce... and failing
I am trying to regroup an array of arrays using reduce... and failing

Time:12-09

So, I am trying to regroup the elements... well in a way that is hard to explain. Here is a sample of input and expected output...

zip(['fred', 'barney'], [30, 40], [true, false]); 

should output...

→ [['fred', 30, true], ['barney', 40, false]]

I thought reduce would be appropriate since I am supposed to take multiple arrays and convert it into a single array that contains the same amount of arrays as the input array's length...

Here is what I am working on... It isn't functioning but I believe I am close to the right idea!

function zip(array) {
    return array.reduce((acc, next) => {
        // get length of next array to use in for-loop...
        let numOfElem = next.length
        // use a for loop to access different indexed arrays...
        for (let i = 0; i < numOfElem; i  ) {
            // this is supposed to push the appropriate element in the next array to the accumulator array's corresponding index...
            acc[i].push(next[i]);
        }
        return acc;
    }, [])
}

const result = zip(['fred', 'barney'], [30, 40], [true, false]); 
console.log(result);

I believe I am attempting to push incorrectly? The idea behind acc[i].push(next[i]) is that acc[i] would create the necessary amount of arrays based off of the length of the input arrays. The code is non-functional. I am just looking for a way to get it working, even if by a different method!

Thanks for taking the time to read this and for any feedback, tips or tricks!

CodePudding user response:

You could reduce the parameters and map the part result of the same index.

const
    zip = (...array) =>
        array.reduce((r, a) => a.map((v, i) => [...(r[i] || []), v]), []);

console.log(zip(['fred', 'barney'], [30, 40], [true, false]));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Approach for unequal lengths of arrays.

const
    zip = (...array) => array.reduce((r, a, i) => {
        while (r.length < a.length) r.push(Array(i).fill(undefined));
        return r.map((b, j) => [...b, a[j]]);
    }, []);

console.log(zip(['fred', 'barney'], [30, 40, 3, 4, 5, 6, 7], [true, false, 'don\'t know']));
.as-console-wrapper { max-height: 100% !important; top: 0; }

CodePudding user response:

function zip(...arrays) {
  const flattened = arrays.flatMap(item => item)
  const result = []
  for (let index = 0; index <= arrays.length; index  ) {
    result[index] = []
    for (let step = index; step < flattened.length; step = step   arrays[0].length) {
      result[index][(step - index) / arrays[0].length] = flattened[step]
    }
  }
  return result
}

const arr1 = [ 'fred', 'barney', 'alpha', 'beta' ]
const arr2 = [ 30, 40, 50, 60 ]
const arr3 = [ true, false, null, true ]

console.log(zip(arr1, arr2, arr3))

CodePudding user response:

Something like this?

const zip=(arr)=>{
    let res=[]
    arr[0].forEach((el,k) => {
        res.push(arr.reduce((acc, curr)=>{
            acc.push(curr[k])
            return acc
        },[]))  
    });
  return res
}
console.log(zip([['moe', 'larry', 'curly'], [30, 40, 50], [true]]))

  • Related