Oscar Godson
Oscar Godson

Reputation: 32726

Replace while loop with lodash

I was trying to find a way in lodash to do this:

var start = 0;
while (rows[start].substring(0, 1) === "#") {
  start++;
}

The actual code is skipping all the top lines until it doesn't find a # at the beginning. I was hoping there was a bit nicer lodash method that I could do something like

var start = _.someMethod(function (str) {
  return str.substring(0, 1) === "#"
})

So basically a lodash method to find the first index that does not match some query. Does that exist?

Upvotes: 1

Views: 3387

Answers (3)

Xotic750
Xotic750

Reputation: 23482

You can compose a specific function, something that lodash is very good at.

var rows = ['#zero', '#one', '#two', 'three', '#four'];
var startsWithHash = _.ary(_.partialRight(_.startsWith, '#'), 1);
var notStartsWithHash = _.negate(startsWithHash);
var findIndexNotStartsWithHash = _.ary(_.partialRight(_.findIndex, notStartsWithHash), 1);
var index = findIndexNotStartsWithHash(rows);
console.log(index); // 3
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

Upvotes: 0

gforce301
gforce301

Reputation: 2984

Assuming rows is an Array. You are looking for _.findIndex

Upvotes: 0

JJJ
JJJ

Reputation: 33163

There's an aptly named _.findIndex().

var rows = [ "#zero", "#one", "#two", "three", "#four" ];

var index = _.findIndex( rows, function (str) {
  return str.charAt(0) !== "#";
});

console.log( index );  // 3
<script src="https://cdn.jsdelivr.net/lodash/4.12.0/lodash.min.js"></script>

Upvotes: 6

Related Questions