Follow @endyourif rss Facebook LinkedIn

ko.utils.arrayFirst using Knockoutjs and Javascript ko.utils.arrayFirst using Knockoutjs and Javascript

Published on Jun 17, 2022

So, you're using KnockoutJS and Javascript and you need to loop an array; are you tired of writing for loops with an if statement followed by break to exit the loop? I know I am, so let's look at a better way to do it. This will be a great addition to my list of KnockoutJS tutorials that you should check out. Enough chat, let's get right to it.



To start, let's look at the old way that makes me cringe!


var myCustomers = ko.observableArray([
{
"companyName": "End Your If"
},
{
"companyName": "Your company"
}
]);

var foundIt = false;

for (var i = 0; i < myCustomers().length; i++) {
var customer = myCustomers()[i];

if (customer.companyName === "End Your If") {
foundIt = true;
break;
}
}


There are a couple of things I wish to point out here. I've made this an observableArray to highlight a couple of Knockout gotchas. As you may have noticed it's important that whenever I access the myCustomers variable I am using () after to access the properties.

Alright, now let's look at an example using ko.utils.arrayFirst to accomplish the same thing.


var myCustomers = ko.observableArray([
{
"companyName": "End Your If"
},
{
"companyName": "Your company"
}
]);

var foundIt = ko.utils.arrayFirst(myCustomers(), function(customer) {
return customer.companyName === "End Your If";
});


That's it, we've replaced that clunky for loop with a single line of code that does some handy things for us:
1. Loops the array
2. Provides a readable variable name
3. Return statement that will exit as soon as it finds a match or returns false if not found at all

One final note, notice that when passing the array to the ko.utils.arrayFirst function that I've added () because this is an observable array.

Tags: Knockout js Tutorial | JavaScript | Knockout js Tutorial | Javascript Arrays Tutorial

My Books
ASP.NET MVC 5 With Bootstrap and Knockout.js
Knockout.js Building Dynamic Client-Side Applications
20 Recipes for Programming MVC 3
20 Recipes for Programming PhoneGap
Rapid Application Development with CakePHP