7

I'm trying to get this nested array to a flat array. While using this way to solve it seems every time I callback arrayFlattener(element) the newArr become a empty array. Can someone help me with this? Thank you.

const arrayFlattener = (arr) => {
    let newArr = [];
    
    for (let i = 0; i < arr.length; i++) {
        let element = arr[i];
        if (Array.isArray(element)){
            newArr.push(arrayFlattener(element));
            
        } else {
            newArr.push(element);
        }
    }
    return newArr;
}
console.log(arrayFlattener(['I', 'am', 'working', ['on', 'another', 'level']]));

3
  • It would be helpful if you tagged this question with the language you're working in. (I'd do it for you, but I don't recognize the syntax.) Commented Mar 8, 2019 at 4:23
  • Is performance the requirement for using recursion? Commented Mar 8, 2019 at 4:50
  • Are you looking for general recursion, tail recursion, or iterative recursion? Commented Mar 8, 2019 at 5:10

5 Answers 5

2

flat do the job with the depth param level specifying how deep a nested array structure should be flattened.

Example

const arr = ['I', 'am', 'working', ['on', 'another', 'level'], 'now', ["now", ["hello", "you you"]]]

console.log(arr.flat(2))

Sign up to request clarification or add additional context in comments.

Comments

2

Your code and theory are fine. You just chose the wrong method. Use concat instead of push (to extend the result rather than insert into it):

const arrayFlattener = (arr) => {
    let newArr = [];
    
    for (let i = 0; i < arr.length; i++) {
        let element = arr[i];
        if (Array.isArray(element)){
            newArr = newArr.concat(arrayFlattener(element));
            
        } else {
            newArr.push(element);
        }
    }
    return newArr;
}
console.log(arrayFlattener(['I', 'am', 'working', ['on', 'another', 'level']]));

Comments

2

You can use flatMap

let newArr = ['I', 'am', 'working', ['on', 'another', 'level']].flatMap(el=>el);

console.log(newArr);

or use flat

var arr1 = [1, 2, [3, 4]];
arr1.flat(); 
// [1, 2, 3, 4]

var arr2 = [1, 2, [3, 4, [5, 6]]];
arr2.flat();
// [1, 2, 3, 4, [5, 6]]

var arr3 = [1, 2, [3, 4, [5, 6]]];
arr3.flat(2); // depth argument to flatten the array
// [1, 2, 3, 4, 5, 6]

1 Comment

I agree, if you need to implement recursion you can do how @Andreas answered but also I believe browser implementation will be faster than implementing a recursion.
1

Currently, your function did not flatten the array, but simply parse through every individual element of the array. It still returns the same array structure.

To flatten the array, you should pass the resulting array as well, so that the individual element can be pushed straight into the resulting array instead of making another array and push it to the resulting array (which produce the same initial array structure)

let newArr = [];
const arrayFlattener = (arr, result) => {
    for (let i = 0; i < arr.length; i++) {
        let element = arr[i];
        if (Array.isArray(element)){
            result = arrayFlattener(element, result);
            
        } else {
            result.push(element);
        }
    }
    return result
}
console.log(arrayFlattener(['I', 'am', 'working', ['on', 'another', 'level'], 'now'], newArr));

2 Comments

Why not use flattenMap?
This seems a little weird. I think it's more common to enter just an input and expect a result rather than entering both an input and a pointer to the result, unless the latter is absolutely necessary.
1

Here's three solutions

You can use .flatMap and recursion or

const flatten = (xs) =>
  Array.isArray(xs) ? xs.flatMap(flatten) : [xs]

const array = ['I', 'am', 'working', ['on', 'another', ['level']]]

console.log(flatten(array))

you can use .reduce and recursion

const flatten = (xs) =>
  xs.reduce(
    (y, x) => y.concat(Array.isArray(x) ? flatten(x) : [x]),
    [])

const array = ['I', 'am', 'working', ['on', 'another', ['level']]]

console.log(flatten(array))

or even better just use .flat

const flatten = (xs) =>
  xs.flat(Infinity)

const array = ['I', 'am', 'working', ['on', 'another', ['level']]]

console.log(flatten(array))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.