Home > other >  Any another way flatten array and remove null value from array in javascript
Any another way flatten array and remove null value from array in javascript

Time:10-13

I am trying to flatten array and remove any undefined value from the one array and I created one solution but I dont think its optimised. Because i used two loops and check if condition always that I think not optimise. so Any one can have any another way to solve this.

Original array :-

[
    [
        {
            "city": "Beijing",
            "placename": "Jingshan Park",
            "overall_rating": 5
        },
        {
            "city": "Beijing",
            "placename": "Beijing Ancient Observatory",
            "overall_rating": 3
        }
    ],
    [
        {
            "city": "Washington, D.C.",
            "placename": "National Air and Space Museum",
            "overall_rating": 4
        },
        null
    ],
    [
        null,
        null
    ],
    [
        null,
        null
    ],
    [
        null,
        null
    ]
]

required output

[
    {
        "city": "Beijing",
        "placename": "Jingshan Park",
        "overall_rating": 5
    },
    {
        "city": "Washington, D.C.",
        "placename": "National Air and Space Museum",
        "overall_rating": 4
    },
    {
        "city": "Beijing",
        "placename": "Beijing Ancient Observatory",
        "overall_rating": 3
    }
]

solution that i made

let result1 = [];
    for(let index = 0;index < data_array.length;index  ){
        if(data_array[index][0] != undefined){
            for(let iindex = 0; iindex < data_array[index].length;iindex  ){
                if(data_array[index][iindex] != undefined){
                    result1.push(data_array[index][iindex])
                }
            }
        }
    }

CodePudding user response:

You can use the flat method from arrays to flatten your array

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat

and then filter only the defined values

const array = [
    [{
        "city": "Beijing",
        "placename": "Jingshan Park",
        "overall_rating": 5
    }, {
        "city": "Beijing",
        "placename": "Beijing Ancient Observatory",
        "overall_rating": 3
    }],
    [{
        "city": "Washington, D.C.",
        "placename": "National Air and Space Museum",
        "overall_rating": 4
    }, null
    ],
    [null, null],
    [null, null],
    [null, null]
]

const arrayFiltered = array.flat().filter(v => v)

console.log(arrayFiltered)
  • Related