开发者

jQuery/JS: Sorting array based upon another array?

开发者 https://www.devze.com 2023-01-30 14:38 出处:网络
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 ho

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 (myAr开发者_运维技巧ray[i].properties[property] === value) 
        newArray.push(myArray[i]);
    }            
    return newArray;
}


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;
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消