Osman Rafi
Osman Rafi

Reputation: 1046

How to print multiple items of a JS object/array in per iteration with map?

I am working in React. I am trying to find out a solution to a mapping problem. While mapping an object or array in javascript, we know it delivers one item of the array/ object in per iteration. For Example:

Consider an array of object like:

const items = [
  {
    id: 1,
    color: "red"
  },
  {
    id: 2,
    color: "blue"
  },
  {
    id: 3,
    color: "yellow"
  },
  {
    id: 4,
    color: "black"
  }
];

Now,

items.map((item, i) => <p key={i}>{item.color}</p>)

This will show an output like :

red
blue
yellow
black

Now what if I want to bring multiple items in per iteration. For Example:

red blue
yellow black

How to do it ? Thanks in advance. Please feel free to use this codesandbox example:

https://codesandbox.io/s/musing-cloud-gnnye?file=/src/App.js:100-339

Upvotes: 0

Views: 477

Answers (2)

Prateek Thapa
Prateek Thapa

Reputation: 4938

You could use the second argument provided by map function which is the current index of the array to find the next item in the array and print accordingly.

You could see the working example here :- https://codesandbox.io/s/mystifying-mccarthy-7fc3o?file=/src/App.js

   const iterate = items.map((item, i) => {
      if (i % 2 !== 0) return null;
  
      const next = items[i + 1] ? items[i + 1].color : "";
      return (
        <p key={i}>
          {item.color} {next}
        </p>
      );
    })
    // you could filter or not, it's up to you. React automatically discards null value
    .filter(x => x);

Upvotes: 1

Dennis Vash
Dennis Vash

Reputation: 53894

This action called "chunk" I would do:

import chunk from "lodash.chunk";

const colors = items.map(({ color }, i) => color);
const chunked = chunk(colors, 2);
const renderPairs = chunked.map(([first, second], i) => (
  <p key={i}>
    {first},{second}
  </p>
));

https://codesandbox.io/s/spring-forest-0pvvq?file=/src/App.js:86-679

Lodash implementation:

function chunk(array, size = 1) {
  size = Math.max(toInteger(size), 0)
  const length = array == null ? 0 : array.length
  if (!length || size < 1) {
    return []
  }
  let index = 0
  let resIndex = 0
  const result = new Array(Math.ceil(length / size))

  while (index < length) {
    result[resIndex++] = slice(array, index, (index += size))
  }
  return result
}

Upvotes: 2

Related Questions