Reputation: 2691
I am currently using lodash map to map over an array of objects.
I always need index 0 in the array to do something different. Is there a way to make map start at index 1, without mutating or messing with the array?
I know that I can use slice(1). Just wondering if there was another way to start from index 1 rather than 0. So I didn't have to join them back together afterwards.
Upvotes: 1
Views: 14154
Reputation: 10009
The second parameter of map accepts a function which has 3 arguments (value, index|key, collection)
.
So you can skip the first value using index
and play with the rest of your data using value
.
Something like this:
let data = [0, 1, 2];
let result = _.map(data, (value, index) => {
if (index === 0) {
return value;
} else {
return value * 2;
}
});
console.log(result);
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>
Upvotes: 9