Home > Back-end >  mapping an array in react
mapping an array in react

Time:06-16

I am fetching an array from a database , the array has strings , and it displays all the desirable elements accordingly like this :

 {blogs.nodes.map((ts)=>
<Component ts={ts} />
)}

what I want exactly is to display only the round of the whole array divided by 2 .Instead of displaying this component 8 times for example , it must displayed only 4 times. this is my array :

{
  "data": {
    "blogs": {
      "nodes": [
        {
          "id": "4a007c39-2053-5c5e-8f38-56ba8c3aced5"
        },
        {
          "id": "9e78be5c-08e7-5684-adaa-b788cb4020b7"
        },
        {
          "id": "f5d3055d-9575-5840-b8d7-b55779671417"
        },
        {
          "id": "00d504ef-458f-5830-8d0e-ae91d33fadc4"
        },
        {
          "id": "a02cb1ae-b4bd-5978-afbf-3c91f6473ae2"
        },
        {
          "id": "b4daa0f7-4249-5bf2-b82d-143811329639"
        },
        {
          "id": "3ebda83d-293c-56ed-9b71-b8d318036086"
        },
        {
          "id": "3d46370e-f574-5be6-83a1-c0386d19b17d"
        }
      ]
    }
  },
  "extensions": {}
}

CodePudding user response:

let half = blogs.nodes.length % 2 
blogs.nodes.slice(0, half).map((node) => {
        return <Component key={node.id} item={node} />
   });

Original Question and answer here

CodePudding user response:

const halfOfBlogs =Math.ceil(blogs.length / 2);
const firstHalf = list.splice(0, half);
const secondHalf = list.splice(-half);

you can loop through the first half or the second half

  • Related