Remove an outer array in JavaScript with the flat method

  • — Javascript

  • 1 min. read

  • — 3/4/2023

The other day I was working on Milk Road's NFT page and one issue I was running into was rendering rows of data while using TanStack Query's useInfiniteQuery hook.

For those that don't know, useInfiniteQuery will return paginated data in a page array. Now, the query I was making already returns rows of NFT data as an array, so roughly speaking this was the data I was working with:

// Returned data from TanStack Query

pages = [
	nft_collections: [
    	{ ... },
        { ... },
        { ... },

Now mind you, one other aspect of useInfiniteQuery is that it makes additional requests and appends additional data to the pages array. So basically, each page is an array and within each page we have an nft_collections array that contains the actual data for the table.

The issue that I was facing was that our table component only accepts an array of NFT table items:

const nft_collections = [{...}, {...}, {...}]

<Table rows={[nft_collections]} />

And the data I was working with basically looked like this:

const pages = [[nft_collections: {...}, {...}, {...}]]

So... basically I needed to remove that outer array entirely.

Good thing there's a method that does just that, it's called flat and it literally just grabs all items of an array (this case, nft_collections) and just puts it in a new array entirely, doing away with the outer pages array entirely.

To use it, I just needed to call flat on pages:


This then returns the following array:

const nft_collections = [{...}, {...}, {...}]

I can then directly pass nft_collections into the Table component and boom, problem solved!

Shaun Chander

hey (again), I'm shaun

I'm posting 3 tips on creative web development daily. Subscribe below to to get tips delivered straight into your inbox!