Elias Ghali
Elias Ghali

Reputation: 853

lodash map skip iteration

i can't seem to find a way to skip an iteration using the lodash _.map, consider this array: checklist =['first','second','third','fourth','fifth','sixth'] i want to map through it with a step of 3 for example, i tried this code but it didn't work:

    _.map(checkList, function(value, key){
  console.log('checkList', firstValue);
console.log('checkList1', secondValue);
console.log('checkList2', thirdValue);
}, 3)

expected output : checkList first , checkList second, checkList third, checkList fourth, checkList fifth, checkList sixth but only with two iterations

something i can achieve using for like this:

    for(let i = 0; i< checkList.length; i+=3){
  console.log('value', checkList[i]);
  console.log('value1', checkList[i+1]);
  console.log('value2', checkList[i+2]);
}

thank you

Upvotes: 3

Views: 6216

Answers (2)

Ori Drori
Ori Drori

Reputation: 191986

Map, filter, forEach, reduce, etc... iterate all items in the array, and you can't skip items. For this tasks, a for loop is quite fitting.

If you want to achieve that with lodash, use _.chunk() to split the array into sub arrays with the required size, and then iterate using _.forEach() (or map, filter, etc...).

var checklist = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth'];

_(checklist)
  .chunk(3)
  .forEach(function(subArr) {
     console.log('checkList', subArr[0]);
     console.log('checkList1', subArr[1]);
     console.log('checkList2', subArr[2]);
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

Upvotes: 1

JLRishe
JLRishe

Reputation: 101690

You're talking about two different operations - one to take each third item and one to transform them. .map transforms all items in the input and I'm not sure why you assume passing a 3 into it would do what you're describing.

To do what you're describing, filter the items first, then map them:

var checkList = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth'];
var thirdItems = _.filter(checkList, function(v, i) {  return i % 3 === 1; });
var result = _.map(thirdItems, function(value, key) { return 'checkList ' + value; });

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

Upvotes: 1

Related Questions