Question

I have 2 arrays :

labels = ["water", "sever", "electricity"];
services = [0:[0:"1",1:"sever"], 1:[0:"3",1:"park"], 3:[0:"4",1:"gas"]];

I want to check if ANY of labels value is in services or not (True or False).

What is the best way to archive this using jquery?

EDIT 1:

Yes, I made a mistake while asking question, services is a JSON Object.

UPDATE

Bregi's 2nd solution is what I needed. .some is fulfilling purpose.

var isInAny = labels.some(function(label) {
  return services.some(function(s) {
    return s[1] == label;
  });
});
Was it helpful?

Solution

Use the some Array method (though you might need to shim it for legacy environments):

var isInAny = labels.some(function(label) {
    // since we don't know whether your services object is an actual array
    // (your syntax is invalid) we need to choose iteration/enumeration
    if (typeof services.length == "number") {
        for (var i=0; i<services.length; i++)
            if (services[i][1] == label)
                return true;
    } else {
        for (var p in services)
            if (services[p][1] == label)
                return true;
    }
    return false;
});

If services is really an Array, you could also use

var isInAny = labels.some(function(label) {
    return services.some(function(s) {
        return s[1] == label;
    });
});

OTHER TIPS

Assuming those should be braces instead of brackets in services

labels.some(function (label) {
    for (var x in services) {
        if (services.hasOwnProperty(x)) {
            return services[x][1] === label;
        }
    }
});

http://jsfiddle.net/WwsLk/

This has often been answered here. You may want to have a look ^^

But, to give you an answer: Use $.each on services to generate a new array with the strings from there and compare this to the labels array.

This should get you an idea: Compare two multidimensional arrays in javascript

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top