简体   繁体   中英

Javascript: Filtering twodimensional array

There's plenty examples available on how to sort an javascript array based on it's numeric values. What would however be appropriate way to fetch all elements from myArray with the property prop1 with it's according value value1 ?

Here's my array:

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

Thanks

You can just access it by dot or bracket notation and push the matching members to your new/filtered array, for example:

var newArray = [];
for(var i=0, l = myArray.length; i<l; i++) {
  if(myArray[i].properties.prop1 == "value1") newArray.push(myArray[i]);
}

Your question is a bit ambiguous though, if you're trying to get the {"prop1":"value1"} object, not the parent, then just change newArray.push(myArray[i]) to newArray.push(myArray[i].properties) .

Provide a compare function to sort by arbitrary properties:

function compareMyObjects(a, b) {
  var valA = a.properties.prop1.value1;
  var valB = b.properties.prop1.value1;

  if(valA > valB) return 1;
  if(valA < valB) return -1;
  return 0;
}

myArray.sort(compareMyObjects);

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort

Go through each element in your array. For each element, check each property to see if it matches the one you're looking for.

function filterArray(array, property, value) {
    var newArray = [];
    for (var i = 0; i < array.length; i++) {
        for (var j in array[i].properties) {
            if (j === property && array[i].properties.hasOwnProperty(j)) {
                if (array[i].properties[j] == value) {
                    newArray.push(array[i]);
                }
            }
        }
    }
}
var newarray=myarray.filter(function(itm){
   return itm.properties.prop1==='value1';
});

Filter, like the array methods indexOf and map, may be worth providing for browsers that don't have it- this version is from Mozilla Developer Site-

if(!Array.prototype.filter){
    Array.prototype.filter= function(fun, scope){
        var L= this.length, A= [], i= 0, val;
        if(typeof fun== 'function'){
            while(i< L){
                if(i in this){
                    val= this[i];
                    if(fun.call(scope, val, i, this)){
                        A[A.length]= val;
                    }
                }
                ++i;
            }
        }
        return A;
    }
}

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