Sam
Sam

Reputation: 2351

Javascript: Iterating over multiple items per loop with map

Typescript also works


Lets say I have an array like this

const array = ['one', 'two', 'three', 'four', 'five']

And I want to produce some components that would look like

  <div>
    one
    two
  </div>
  <div>
    three
    four
  </div>
  <div>
    five
  </div>

If I wanted to use the map function, to the best of my knowledge I would have to write something like

{
  let saved
  array.map((item) => {
    if (saved === ''){
      let temp = saved
      saved = ''
      return (  
        <div>{`${item} ${temp}`}</div>
      )
    }else{
      saved = item
    }
  })
}

But I would like to clean this code up a bit. I'm looking for a way that I can use the map function(or forEach) to iterate over the array moving across 2+ items at a time, so that the above code could be shortened to something like below, and produce the same result.

array.map((item1, item2) => <div>{`${item1} ${item2}`}</div>)

Upvotes: 0

Views: 2127

Answers (4)

Shubham Singh
Shubham Singh

Reputation: 1

You can just use the slicing method to divide the array in parts.Try this

const displayChunk=(arr)=>
{
  let newArr=[];
  for(let i=0;i<arr.length;i+=2)
  {
    newArr.push(arr.slice(i,i+2));
  }
return newArr.map(el=><div>{el[0]}</div>{el[1]? <div>{el[1]}</div>:""})


 }


Upvotes: 0

max
max

Reputation: 467

let htmlString = ``

let biArray = [['one', 'two'], ['three', 'four']]

biArray.map(function(elem) {

    htmlString = [...htmlString, `<div>${elem[0]} ${elem[1]}</div>`]
    // console.log(htmlString)

})

Upvotes: 0

Quentin Grisel
Quentin Grisel

Reputation: 4987

Just use a for loop with i+2 instead of i++ ?

const displayValue = () => {
    let content;

    for(let i = 0; i <= array.length; i+2){
      content += <div>{array[i]} {i+1 <= array.length ? array[i+1] : ''}</div>
    }

    return content;
  };

Don't know your use case but here is the idea. Just be careful about i+1 that can be out of bound if your array contains 5 elements for example.

Upvotes: 1

jobayersozib
jobayersozib

Reputation: 409

const chunk = (arr, size) =>
  Array.from({ length: Math.ceil(arr.length / size) }, (v, i) =>
    arr.slice(i * size, i * size + size)
  );
let arr=chunk([1, 2, 3, 4, 5], 2);

arr.map(item=> item.length>1 ? `<div>${item[0]}${item[1]}</div>` : `<div>${item[0]}</div>` )

Use lodash chunk method follw this link

Upvotes: 1

Related Questions