skip to Main Content

I have the below function, but it is not returning the desired result. How can I change this so it returns the desired output?

function convertArr () {

const separateNestedArrays = function (arr) {
  return arr.flatMap((element) => {
    if (Array.isArray(element)) {
      return element;
    } else {
      return [element];
    }
  });
};

const twoDimensionalArray = [
  [1, 2, 3, 4],
  [[5, 6], [9, 10]],
  [5, 6, 7]
];

const modifiedArray = separateNestedArrays(twoDimensionalArray);

console.log(modifiedArray);

// Desired Output: [[1, 2, 3, 4], [5, 6], [9, 10], [5, 6, 7]]
// Current Output: [ 1, 2, 3, 4, [ 5, 6 ], [ 9, 10 ], 5, 6, 7 ]

};

4

Answers


  1. You could work with recursive functions but in your case if twoDimensionalArray is not going to be more than 2 dimensions this code could work :

    const separateNestedArrays = function (arr) {
      let result=[]
      arr.map((element) => {
        if (Array.isArray(element[0])) {
            element.flatMap((subArray) => {
                result.push(subArray)
            })
        } else {
            result.push(element)
        }
      });
      return result
    };
    
    const twoDimensionalArray = [
      [1, 2, 3, 4],
      [[5, 6], [9, 10]],
      [5, 6, 7]
    ];
    
    
    console.log(separateNestedArrays(twoDimensionalArray));
    
    Login or Signup to reply.
  2. That one is tricky. Flatmap doesn’t apply it’s flattening until the return, so you can’t work directly with it inside the handler. I think it’s a good opportunity for using Array.reduce

    function convertArr() {
      const separateNestedArrays = (arr) => arr.reduce((b, a) => {
        if (Array.isArray(a[0])) a.forEach(aa => b.push(aa));
        else b.push(a);
        return b;
      }, []);
    
      const twoDimensionalArray = [
        [1, 2, 3, 4],
        [
          [5, 6],
          [9, 10]
        ],
        [5, 6, 7]
      ];
    
      const modifiedArray = separateNestedArrays(twoDimensionalArray);
    
      console.log(modifiedArray);
    
      // Desired Output: [[1, 2, 3, 4], [5, 6], [9, 10], [5, 6, 7]]
      // Current Output: [ 1, 2, 3, 4, [ 5, 6 ], [ 9, 10 ], 5, 6, 7 ]
    
    };
    
    convertArr();
    Login or Signup to reply.
  3. The function you want should flatten a single level if the array items also contains another array?

    I’d write this using reduce, where you push your items into your accumulator (a new array).

    If the item contains another array, then push the items’ subitems, otherwise push the item itself.

    That is confusing to type out, seeing some code might be easier.

    const separateNestedArrays = (arr) => {
      return arr.reduce((acc, item) => {
        // If our item array also contains other arrays, flatten one level.
        if (Array.isArray(item) && item.some(subItem => Array.isArray(subItem))) {
          item.forEach(subItem => {
            acc.push(subItem);
          });
        } else {
          // Otherwise also include the item
          acc.push(item);
        }
        
        return acc;
      }, []);
    }
    
    const twoDimensionalArray = [
      [1, 2, 3, 4],
      [[5, 6], [9, 10]],
      [5, 6, 7]
    ];
    
    const modifiedArray = separateNestedArrays(twoDimensionalArray);
    
    console.log(JSON.stringify(modifiedArray));
    Login or Signup to reply.
  4. Every time you encounter an array, create a new array in the accumulator (a). Then recursively push further items into the most recent array in the accumulator.

    Finally, discard any empty arrays in the result.

    const input = [[1, 2, 3, 4], [[5, 6], [9, 10]], [5, 6, 7]];
    
    const f = (i, a=[]) => (Array.isArray(i) ?
      (a.push([]), i.forEach(j=>f(j, a))) : a[a.length-1].push(i), a)
    
    console.log(f(input).filter(i=>i.length))
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search