简体   繁体   中英

How to filter multidimensional JavaScript array

I have this data:

var object = [{
    "nid": "31",
    "0": {
        "tid": "20",
        "name": "Bench Press",
        "objectDate": "2012-02-08",
        "goal": "rep",
        "result": "55.00",
        "comments": "sick!",
        "maxload": "250"
    },
    "1": {
        "tid": "22",
        "name": "Back Squat",
        "objectDate": "2012-02-08",
        "goal": "time",
        "result": "8.00",
        "comments": "i was tired.",
        "maxload": "310"
    }},
{
    "nid": "30",
    "0": {
        "tid": "19",
        "name": "Fran",
        "objectDate": "2012-02-07",
        "goal": "time",
        "result": "5.00",
        "comments": null
    }}];

and I would like to filter it by name. For instance, if I apply a filter for the name "Fran", I'd like to have something like this:

[0] => Array
     (
        [tid] => 19
        [name] => Fran
        [objectDate] => 2012-02-07
        [goal] => time
        [result] => 5.00
        [comments] => 
     )
[1] => Array
     (
        [tid] => 19
        [name] => Fran
        [objectDate] => 2012-02-08
        [goal] => rep
        [result] => 55.00
        [comments] => woohoo!
     )

Is it possible to achieve?

There is no function for this in Javascript. You have to write your own function like this.

var arr = [{"nid":"31","0":{"tid":"20","name":"Bench Press","objectDate":"2012-02-08","goal":"rep","result":"55.00","comments":"sick!","maxload":"250"},"1":{"tid":"22","name":"Back Squat","objectDate":"2012-02-08","goal":"time","result":"8.00","comments":"i was tired.","maxload":"310"}},{"nid":"30","0":{"tid":"19","name":"Fran","objectDate":"2012-02-07","goal":"time","result":"5.00","comments":null}}];


function filterByProperty(array, prop, value){
    var filtered = [];
    for(var i = 0; i < array.length; i++){

        var obj = array[i];

        for(var key in obj){
            if(typeof(obj[key] == "object")){
                var item = obj[key];
                if(item[prop] == value){
                    filtered.push(item);
                }
            }
        }

    }    

    return filtered;

}

var byName = filterByProperty(arr, "name", "Fran");
var byGoal = filterByProperty(arr, "goal", "time");

The question is about multidimensional arrays. If you like me missed that here are solutions for normal arrays...

2020

filteredArray = array.filter(item => item.name.indexOf('Fran') > -1);

or

filteredArray = array.filter(function(item)
{
    return item.name.indexOf('Fran') > -1);
}

2012 version

var result = [];
for (var i = 0; i < array.length; i++)
{
    if (array[i].name === 'Fran')
    {
        result.push(array[i]);
    }
}

I would create a function for filtering :

function filter(array, key, value){
    var i, j, hash = [], item;

    for(i =  0, j = array.length; i<j; i++){
        item = array[i];
        if(typeof item[key] !== "undefined" && item[key] === value){
            hash.push(item);
        }
    }

    return hash;
}

A more robust solution might be adding a filter method to the prototype:

    `This prototype is provided by the Mozilla foundation and
     is distributed under the MIT license.
     http://www.ibiblio.org/pub/Linux/LICENSES/mit.license`

if (!Array.prototype.filter)
{
  Array.prototype.filter = function(fun /*, thisp*/)
  {
    var len = this.length;
    if (typeof fun != "function")
      throw new TypeError();

    var res = new Array();
    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
    {
      if (i in this)
      {
        var val = this[i]; // in case fun mutates this
        if (fun.call(thisp, val, i, this))
          res.push(val);
      }
    }

    return res;
  };
}

Then simply call:

function filterName (item, index, array) {
  return (item.name === "Fran");
}

var result = object.filter(filterName);

If your object contains 3 fields, say email, firstName, lastName then you use this.

ArrayObject
.filter(em => em.email.indexOf(searchEmail) > -1)
.filter(fn => fn.firstName.indexOf(searchFirstName) > -1)
.filter(ln => ln.lastName.indexOf(searchLastName) > -1) 

The big trick is to make a flat array with just the item you want in it.

say you have a 2d array like so:

e = [[1,2],[1,2],[2,3],[4,5],[6,7]]

you make a new array:

var f = []

fill it with just 1 item:

for(var x=0;x<e.length;x++) f[x] = e[x][1]

giving us the likes of:

f = [2,2,3,5,7]

and then....

var g = e.filter( function(elem, pos){ return (f.indexOf(elem[1]) == pos) })

cowabunga!

I try the solution from Diode. I adapt for my case. There are 3 arrays included.

var arr = 
[

  {
    taskTypeGroupId: "EXP.CONT", taskTypeGroupName: "Contradictoire", 
    taskType: 
    {
      taskTypeId: "DGE-EXPCONT", taskTypeName: "Dégats des eaux contradictoire", defaultDuration: 60, isInProject: false, 
      dataItems:
      {
        id: "EXTRAFILLER5", label: "Divers 5"
      }
    }
  },

  {
  takTypeGroupId: "EXPQUAL", taskTypeGroupName: "Contrôle qualité", 
    taskType: 
    {
      taskTypeId: "DGE-EXPQUAL", taskTypeName: "Contrôle qualité dégats des eaux", defaultDuration: 60, isInProject: false, 
      dataItems: 
      {
        id: "EXTRAFILLER5", label: "Divers 5"
      }
    }
  }

];
function filterByProperty(array, prop, value){
var filtered = [];

for(var i = 0; i < array.length; i++){
var array1 = array[i];
  for(var key in array1){
    if(typeof(array1[key] == "object")){
    var array2 = array1[key];
      for (var key2 in array2){
        if(typeof(array2[key2] == "object")){
        var array3 = array2[key2];
          if(array3[prop] == value){
            filtered.push(array3);
          }
        }
      }
    }
  }
}    
return filtered;

}

JsBin example

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