skip to Main Content

This is the original array I want to convert:

const baseArray = [1, 2, 3, [4, 5, [6, 7]], 8, 9, [10, 11, [12, 13]], [14, 15]];

and this is the result I want:

const result = [
    [1, 2, 3, 8, 9],
    [4, 5, 10, 11, 14, 15],
    [6, 7, 12, 13]
  ];

This separation is based on the depth of the array

6

Answers


  1. You can iterate through items in array and checking they depth:

    function separateByDepth(arr) {
      function flattenAndOrganize(array, depth, result) {
        for (const item of array) {
          if (Array.isArray(item)) {
            if (!result[depth]) {
              result[depth] = [];
            }
            flattenAndOrganize(item, depth + 1, result);
          } else {
            if (!result[depth]) {
              result[depth] = [];
            }
            result[depth].push(item);
          }
        }
      }
    
      const result = [];
      flattenAndOrganize(arr, 0, result);
    
      return result;
    }
    
    const baseArray = [1, 2, 3, [4, 5, [6, 7]], 8, 9, [10, 11, [12, 13]], [14, 15]];
    const separatedArray = separateByDepth(baseArray);
    
    console.log(separatedArray);
    Login or Signup to reply.
  2. This is a good fit for a recursive solution. We’ll write a function that handles the elements of the array it’s given if they aren’t arrays, or calls itself if they are, passing along the target array and the target index in it. So elements at the top level we’ll add to an array at index 0, but the first time we recurse we’ll add to an array at index 1, etc.

    function split(array, target = [], index = 0) {
        // Loop through the elements of the array
        for (const element of array) {
            // Is this element an array?
            if (Array.isArray(element)) {
                // Yes, recurse
                split(element, target, index + 1);
            } else {
                // No, create the array if needed, then push to it
                target[index] ??= [];
                target[index].push(element);
            }
        }
        return target;
    }
    

    Live example:

    function split(array, target = [], index = 0) {
        // Loop through the elements of the array
        for (const element of array) {
            // Is this element an array?
            if (Array.isArray(element)) {
                // Yes, recurse
                split(element, target, index + 1);
            } else {
                // No, create the array if needed, then push to it
                target[index] ??= [];
                target[index].push(element);
            }
        }
        return target;
    }
    
    const baseArray = [1, 2, 3, [4, 5, [6, 7]], 8, 9, [10, 11, [12, 13]], [14, 15]];
    
    const result = split(baseArray);
    console.log(JSON.stringify(result, null, 4));
    .as-console-wrapper {
        max-height: 100% !important;
    }
    Login or Signup to reply.
  3. A good way to do that is to iterate over the baseArray and use a recursive function to complete the result variable depending on the depth you are browsing

    const baseArray = [1, 2, 3, [4, 5, [6, 7]], 8, 9, [10, 11, [12, 13]], [14, 15]];
        // Returns a new array containing other arrays depending on elements depth
        const results = [];
    
        const reArrangeArrayByDepth = (array, depth = 0) => {
            for (let i = 0; i < array.length; i++) {
                if (!Array.isArray(array[i])) {
                    if(!results[depth]) results[depth] = [];
                    results[depth].push(array[i]);
                }
                else {
                    reArrangeArrayByDepth(array[i], depth + 1);
                }
            }
            return depth;
        }
    
        reArrangeArrayByDepth(baseArray)
        
        console.log(results);
    Login or Signup to reply.
  4. const baseArray = [1, 2, 3, [4, 5, [6, 7]], 8, 9, [10, 11, [12, 13]], [14, 15]];
    
    const result = []
    
    function extractElements(array, level){
        array.forEach(element => {
            if(Array.isArray(element)){
                extractElements(element, level + 1)
            } else {
                result[level] ? result[level].push(element) : result[level] = [element]
            }
        })
    }
    
    extractElements(baseArray, 0);
    console.log(result);
    
    Login or Signup to reply.
  5. function separateArrayByDepth(arr) {
      const result = [];
      
      function traverse(array, depth) {
        result[depth] = result[depth] || [];
        
        array.forEach((element) => {
          if (Array.isArray(element)) {
            traverse(element, depth + 1);
          } else {
            result[depth].push(element);
          }
        });
      }
      
      traverse(arr, 0);
      return result.filter((subArray) => subArray.length > 0);
    }
    
    const baseArray = [1, 2, 3, [4, 5, [6, 7]], 8, 9, [10, 11, [12, 13]], [14, 15]];
    
    const result = separateArrayByDepth(baseArray);
    console.log(result);
    Login or Signup to reply.
  6. You could take a recursive approach by handing over an index for level and result array.

    const 
        getLevel = (array, index = 0, result = []) => {
            for (const value of array) {
                if (Array.isArray(value)) getLevel(value, index + 1, result);
                else (result[index] ??= []).push(value);
            }
            return result;
        },
        data = [1, 2, 3, [4, 5, [6, 7]], 8, 9, [10, 11, [12, 13]], [14, 15]],
        result = getLevel(data);
    
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search