0

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

1
  • 2
    thats where the for loop shines vs map Commented Sep 17, 2020 at 12:06

2 Answers 2

2

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

Here is a simple implementation of chunk: function chunk(arr, size) { const chunks = []; for (let i = 0; i < arr.length; i += size) {chunks.push(arr.slice(i, i + size));} return chunks;}
1

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

3 Comments

This will create overlapping pairs, whereas it seems OP doesn't want to repeat the array values.
Well, but it's iteration an item twice. How to make "red, blue" & "yellow,black" ?
@OsmanRafi I've updated the code to fit your needs. I don't think you need a library for chunking for a simple task, a simple even number check would do.

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.