Time execution

Benchmark publishedon

Test Runner

Initializing...

Testing in
Test CaseOps/sec
test1
let array1 = [1, 2, 3, [4,5], 6, 7, 8, 9,[111,222,[231,2411,[222,333,[5555555,5555555,[12039123,123012312]]]]]];

function flat(arr, wArr = []) {
  if (Array.isArray(arr)) {
    for (let i = 0; i < arr.length; i++) {
      if (Array.isArray(arr[i])) {
        // Recursively flatten nested arrays
        flat(arr[i], wArr);
      } else {
        // Push non-array items to the result array
        wArr.push(arr[i]);
      }
    }
  } else {
    // Handle non-array input if needed
    wArr.push(arr);
  }
  return wArr;
}

let result1 = flat(array1);
console.log(result1);  // Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
ready
test2
let array = [1, 2, 3, [4,5], 6, 7, 8, 9,[111,222,[231,2411,[222,333,[5555555,5555555,[12039123,123012312]]]]]];

function flat(arr) {
  let result = [];
  let stack = [...arr];  // Use a stack to avoid recursion depth limits.

  while (stack.length > 0) {
    let curr = stack.pop();
    if (Array.isArray(curr)) {
      stack.push(...curr);  // Flatten the array by spreading it onto the stack.
    } else {
      result.push(curr);  // Add non-array values directly to the result.
    }
  }

  return result.reverse();  // Reverse to get the correct order after popping from stack.
}

let result = flat(array);
console.log(result);  // Output: [1, 2, 3, 4, 5]
ready
test3
let array = [1, 2, 3, [4,5], 6, 7, 8, 9,[111,222,[231,2411,[222,333,[5555555,5555555,[12039123,123012312]]]]]];


function flat(arr) {
  let result = [];
  let stack = [arr];  // Start with the initial array

  while (stack.length > 0) {
    let curr = stack.pop();  // Pop the last element

    if (Array.isArray(curr)) {
      // If it's an array, push its elements onto the stack to be processed
      stack.push(...curr);
    } else {
      // If it's a non-array element, push it to the result
      result.push(curr);
    }
  }

  return result.reverse();  // Reverse the result to maintain the original order
}

let result = flat(array);
console.log(result);  // Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.

Revision 1
publishedon