Search code examples
javascriptarrayslodash

Restart iterating for loop from beginning once looping ends - JS


I have an array and an array of objects.

I need to basically map the first element of the array to the first element of the object inside the array and so on.

Both the arrays can be of variable length and the looping should start from the beginning again once the loop ends.

However, I am not sure to start the loop again.

This is my code.

const colors = ['#7cb5ec', '#434348', '#90ed7d', '#f7a35c']

const obj = [{
    name: 'Toyota'
  },
  {
    name: 'Honda'
  },
  {
    name: 'Buick'
  },
  {
    name: 'Chevy'
  },
  {
    name: 'Ford'
  },
  {
    name: 'Toyota'
  }
]

_.forEach(obj, (item, index) => {
  item.color = colors[index]
})

console.log(obj)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

So for Ford and Toyota, it should start from the first. Please advice.


Solution

  • You can use % operator to start the array from 0 index again:

    const colors = ['#7cb5ec', '#434348', '#90ed7d', '#f7a35c']
    
    const obj = [
      {name: 'Toyota'}, {name: 'Honda'}, {name: 'Buick'},
      {name: 'Chevy'}, {name: 'Ford'}, {name: 'Toyota'}
    ];
    
    _.forEach(obj, (item, index) => {
      item.color = colors[index % colors.length]
    });
    
    console.log(obj);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>