Click here to Skip to main content
15,867,308 members
Articles / Knockout.js
Tip/Trick

Knockout Compare Array List

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
21 Feb 2016CPOL 12.7K   2  
Comparing arrays in knockout

Introduction

While using Knockout, we want to compare two array members we can loop through items and compare variables by index. This is useful when we want to compare two array list and check if there are any similar values like filename already existing in arraylist and we can notify user of duplicate values.

JavaScript Code Sample

JavaScript code sample is shown below to declare two var array lists and compare both in knockout using ko.utils.arrayForEach. And match properties while indexing through array loop. Please see the script code below:

JavaScript
//
// declare knockout variable
var imageList = ko.observableArray();
var previousImageList = ko.observableArray();
var duplicateList = ko.observableArray();

var data = {
                "ID1": 1,
                "Val1": "Value1",
                "Val2": "Value3",
                "Val4": "Value4"
            };

            var data1 = {
                "ID1": 2,
                "Val1": "Value5",
                "Val2": "Value3",
                "Val4": "Value2"
            };

            imageList.push(data);

            previousImageList.push(data);

            previousImageList.push(data1);

            ko.utils.arrayForEach(previousImageList(), function (item) {
                
                for (var index = 0; index < imageList().length; index++) {
                    if (imageList()[index].Val4 == item.Val4)
                        duplicateList.push(item);
                }

            });
            console.log(previousImageList());
//

Conclusion

It is a simple script to check if that value is already existing in knockout array list.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --