0

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>)

4 Answers 4

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

2 Comments

Yeah this is the general idea, it'd be awesome if something could summarize this though like the map function does, and take into account the i+1 bounds issue as well
@Sam I edited my answer, cannot test on stackblitz it's broken but i think it should do the job
0
let htmlString = ``

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

biArray.map(function(elem) {

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

})

1 Comment

This would involve initializing the array as a 2d array, I'm talking about using a 1d array to solve this problem, because then I can make it more flexible and group by 3 or 4 if I change my mind
0

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>:""})


 }


Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.