Home > Enterprise >  How can I find the lengths of all subarrays within a chunk array
How can I find the lengths of all subarrays within a chunk array

Time:09-29

I am trying to build a slider and the way it works requires me to chunk my initial data into one array with smaller sub-arrays and also get the length of each subarray. The whole total length.

My data is coming from WordPress and below is my chunk code function.

const chunkArray = (arr, value)=> {
        const finalArray = [];
        for(let i = 0; i < arr.length; i =value){
          finalArray.push(arr.slice(i, value   i))
        }
        return finalArray;
    }

I get my array from this graphql query

const RockstarListCardContent = useStaticQuery(graphql`
    query MyQuery {
        allWpTeamMember {
          nodes {
            slug
            acf {
              field
              firstName
              fieldGroupName
              fullName
              subtitle
              bioHeading
            }
            featuredImage {
              node {
                srcSet
                localFile {
                  childImageSharp {
                    gatsbyImageData
                  }
                  publicURL
                }
                altText
              }
            }
          }
        }
      }
      
`)

I can call my chunk array function like this : chunkArray(RockstarListCardContent.allWpTeamMember.nodes, 8)

What I am trying to do is get each subarray length into one total length. Lets say the data coming from wordpress is around 40 that comes down to 5 chunks of 8 length sub arrays. How can I get the 40 total number from the subarray.

CodePudding user response:

One way to do it is to use the reduce function of arrays. We're setting the initial value to 0 and then adding all the subArrays lengths one by one.

    const result = chunkArray(RockstarListCardContent.allWpTeamMember.nodes, 8);
    const totalLength = result.reduce((acc, subArr) => acc   subArr.length, 0);

CodePudding user response:

Get the length from RockstarListCardContent.AllWpTeamMember.nodes.length instead.

  • Related