Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

109
Views
Flatten an array

I want to flatten an array with javascript but without recurssion and without prebuilt function.

This is the code but it dose not flatten the whole array and i want to know what is wrong with my code

input : [1, [2], [3,8, [[4]],9],[5,6]]
output : [1, 2, 3, 8, 5, 6]

Code :

flat = function(array) {
  const output = []
  for (let i = 0; i < array.length; i++) {
    if (typeof array[i] == 'number') {
      output.push(array[i])
    } else {
      let arr = array[i]

      let n = 0
      while (n < arr.length) {
        if (typeof arr[n] == 'number') {
          output.push(arr[n])
          n++
        } else {
          arr = arr[n]
          n--
          console.log(arr, n);
        }
      }
    }
  }
  return output
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

It's possible to do, but it involves managing a stack yourself, manually:

const input = [1, [2], [3, 8, [[4]], 9], [5, 6]];

const result = [];
const stack = [{current: input, pos: 0}];
while (stack.length > 0) {
  let {current, pos} = stack.pop();
  if (pos < current.length) {
    let item = current[pos++];
    stack.push({current, pos});
    if (Array.isArray(item)) {
      stack.push({current: item, pos: 0});
    } else {
      result.push(item);
    }
  }
}

console.log(result);

This is what a recursive approach would do in the background, more or less. If your concern about recursion was that you don't like/understand it, not sure that you will find this one more likeable.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!