Home > OS >  How do I get the X indexed element from every nested array?
How do I get the X indexed element from every nested array?

Time:08-08

I may be overthinking this, but say I have this example

    const array = [
        [{name: 'hello', key: 1}, {name: 'foo', key 2}],
        [{name:'bar', key: 3}]
    ];

I want to be able to group everything based on its index in the original array.

mysteriousFunction(array)
output:
   [
     // Index 0
     [{name: 'hello', key: 1}, {name:'bar', key: 3}],
     
      // Index 1
      [{name: 'foo', key 2}]
   ]

I believe I might be able to achieve this with reduce, but I don't know.

CodePudding user response:

Here is my solution

    const inputArr = [
     [
        { name: "hello", key: 1 },
        { name: "foo", key: 2 },
     ],
     [{ name: "bar", key: 3 }],
    ];

    const mysteriousFn = (arr) => {
        const newItemList = [];
        
        arr.map((item) => {
            item.map((i, idx) => {
                if (newItemList[idx] !== undefined) {
                    newItemList[idx].push(i);
                } else {
                    newItemList.push([i]);
                }
            });
        });
    
        console.log("---- new list ----", newItemList);
        return newItemList;
    };
    
    mysteriousFn(inputArr);

Hope this might help you solve your problem.

  • Related