简体   繁体   中英

Trouble at comparing arrays

I have 'shared.checkedFacility' scope array in controller which read something like:

[14, 49, 93, 122, 44, 40, 88, 83, 65, 9, 38, 28, 8, 53, 125, 155]

and i am dynamically generating two dimensional array in front end where, for example, single dimentional array from ' shared.facilities[$parent.$index] ' read like

{"0":56,"1":13,"2":49,"3":3,"4":11,"5":7,"6":19,"7":4,"8":9,"9":131,"10":21}

Now i am comparing this two array in ng-show argument like

containsAny(shared.checkedFacility,shared.facilities[$index])

Where as function defination is like

function containsAny(source, target) {
        console.log("contains called");
        var result = source.filter(function(item) {
            return target.indexOf(item) > -1
        });
        return (result.length > 0);
    }

But some how this function is not returning true or false, how to make it work?

Please rescue me since i am afresh here in Angular or in Javascript Env straight from PHP.

You can use Object.keys() , .map() to create an array from shared.facilities[$parent.$index]

 // `shared.checkedFacility` var checkedFacility = [14 , 49 , 93 , 122 , 44 , 40 , 88 , 83 , 65 , 9 , 38 , 28 , 8 , 53 , 125 , 155 ]; // shared.facilities[$parent.$index] var facilities = { "0": 56, "1": 13, "2": 49, "3": 3, "4": 11, "5": 7, "6": 19, "7": 4, "8": 9, "9": 131, "10": 21 }; // create an array having values contained in `facilities` var arr = Object.keys(facilities).map(function(prop, index) { return facilities[prop] }); console.log(arr) function containsAny(source, target) { console.log("contains called"); var result = source.filter(function(item) { return target.indexOf(item) > -1 }); return (result.length > 0); } // pass `arr` as second parameter to `containsAny` var res = containsAny(checkedFacility, arr); console.log(res) 

Your function is failing on:

target.indexOf(item)

because target in your example is an Object and not an Array , so you can't call indexOf function.

So you are most likely getting:

Uncaught TypeError: target.indexOf is not a function

To solve that, you have to pass an Array as target instead of passing an Object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM