Hi everyone,

I want to sort a JSON object/array (shown below as myArray), upon values from another array - very close to the MYSQL query MYSQL WHERE IN(1,2,3). I was able to get a great answer by Nick Craver on how to sort by one property and value, but how can I do this with multiple values from my other array?

Here's my dataset Json array:

var myArray = [
{
    "id":"2",
    "name":"My name",
    "properties":{"prop1":"value1"}
}];

And the array which I want to sort upon (serialized, coming straight from a form):

var sortArray = [ { "prop1":"value1","prop2":"value2" }];

The current sorting function as it looks right now (courtesy Nick Craver):

function filterDataset(property, value){
    var newArray = [];

    for (var i = 0, l = myArray.length; i < l; i++) {
        if (myArray[i].properties[property] === value) 
        newArray.push(myArray[i]);
    }            
    return newArray;
}
link|flag

Small error in the function - now corrected. – Industrial Dec 13 at 20:16
Maybe you should clarify your objective. It sounds like you are wanting to sort the elements of an array, but your given array only has one element. – Bobby Eickhoff Dec 13 at 20:19
Hi! The Array has only one item in it to become a bit more readable. I want to sort the myArray array as if I were running a || comparision, like user 500894 suggests below, but with an unknown number of properties.. – Industrial Dec 13 at 20:24

2 Answers

up vote 1 down vote accepted

Here's how I managed to fix it:

function filterDataset2(properties){
    var newArray = [];

    for (var i = 0, l = dataset.length; i < l; i++) {

        $.each(properties, function(){
            if (dataset[i].properties[this.name] === this.value) 
                newArray.push(myArray[i]);            
        });

    }

    return newArray;
}
link|flag

This may not be what you mean, but if you have a known list of properties, could you just || your comparison? Say you have 2 properties...

  function filterDataset(property, value){
    var newArray = [];

    for (var i = 0, l = myArray.length; i < l; i++) {
        if ((dataset[i].egenskaper[property1] === value) || (dataset[i].egenskaper[property2] === value) ) 
        newArray.push(myArray[i]);
    }            
    return newArray;
}

Otherwise if the length of the sorting array is unknown you could use a array.find type method that will return true if the property is found within the array in question. If it returns true, just push that value on your newly sorted array.

link|flag
Hi! That is how I want it to be filtered with OR / || comparisions, but based upon the keys&values in my shown array (currently serialized)... – Industrial Dec 13 at 20:26
Thanks for your help - pointed me in the right direction! – Industrial Dec 13 at 20:40

Your Answer

 
or
never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.