65.9K
CodeProject is changing. Read more.
Home

Knockout Compare Array List

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0 vote)

Feb 14, 2016

CPOL
viewsIcon

13172

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:

//
// 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.