[javascript] javascript filter array of objects

I have an array of objects and I'm wondering the best way to search it. Given the below example how can I search for name = "Joe" and age < 30? Is there anything jQuery can help with or do I have to brute force this search myself?

var names = new Array();

var object = { name : "Joe", age:20, email: "[email protected]"};
names.push(object);

object = { name : "Mike", age:50, email: "[email protected]"};
names.push(object);

object = { name : "Joe", age:45, email: "[email protected]"};
names.push(object);

This question is related to javascript jquery arrays

The answer is


You could utilize jQuery.filter() function to return elements from a subset of the matching elements.

_x000D_
_x000D_
var names = [_x000D_
    { name : "Joe", age:20, email: "[email protected]"},_x000D_
    { name : "Mike", age:50, email: "[email protected]"},_x000D_
    { name : "Joe", age:45, email: "[email protected]"}_x000D_
   ];_x000D_
   _x000D_
   _x000D_
var filteredNames = $(names).filter(function( idx ) {_x000D_
    return names[idx].name === "Joe" && names[idx].age < 30;_x000D_
}); _x000D_
_x000D_
$(filteredNames).each(function(){_x000D_
     $('#output').append(this.name);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="output"/>
_x000D_
_x000D_
_x000D_


You can do this very easily with the [].filter method:

var filterednames = names.filter(function(obj) {
    return (obj.name === "Joe") && (obj.age < 30);
});

You will need to add a shim for browsers that don't support the [].filter method: this MDN page gives such code.


For those who want to filter from an array of objects using any key:

_x000D_
_x000D_
function filterItems(items, searchVal) {_x000D_
  return items.filter((item) => Object.values(item).includes(searchVal));_x000D_
}_x000D_
let data = [_x000D_
  { "name": "apple", "type": "fruit", "id": 123234 },_x000D_
  { "name": "cat", "type": "animal", "id": 98989 },_x000D_
  { "name": "something", "type": "other", "id": 656565 }]_x000D_
_x000D_
_x000D_
console.log("Filtered by name: ", filterItems(data, "apple"));_x000D_
console.log("Filtered by type: ", filterItems(data, "animal"));_x000D_
console.log("Filtered by id: ", filterItems(data, 656565));
_x000D_
_x000D_
_x000D_

filter from an array of the JSON objects:**


_x000D_
_x000D_
var nameList = [_x000D_
{name:'x', age:20, email:'[email protected]'},_x000D_
{name:'y', age:60, email:'[email protected]'},_x000D_
{name:'Joe', age:22, email:'[email protected]'},_x000D_
{name:'Abc', age:40, email:'[email protected]'}_x000D_
];_x000D_
_x000D_
var filteredValue = nameList.filter(function (item) {_x000D_
      return item.name == "Joe" && item.age < 30;_x000D_
});_x000D_
_x000D_
//To See Output Result as Array_x000D_
console.log(JSON.stringify(filteredValue));
_x000D_
_x000D_
_x000D_

You can simply use javascript :)


So quick question. What if you have two arrays of objects and you would like to 'align' these object arrays so that you can make sure each array's objects are in the order as the other array's? What if you don't know what keys and values any of the objects inside of the arrays contains... Much less what order they're even in?

So you need a 'WildCard Expression' for your [].filter, [].map, etc. How do you get a wild card expression?

var jux = (function(){
    'use strict';

    function wildExp(obj){
        var keysCrude = Object.keys(obj),
            keysA = ('a["' + keysCrude.join('"], a["') + '"]').split(', '),
            keysB = ('b["' + keysCrude.join('"], b["') + '"]').split(', '),
            keys = [].concat(keysA, keysB)
                .sort(function(a, b){  return a.substring(1, a.length) > b.substring(1, b.length); });
        var exp = keys.join('').split(']b').join('] > b').split(']a').join('] || a');
        return exp;
    }

    return {
        sort: wildExp
    };

})();

var sortKeys = {
    k: 'v',
    key: 'val',
    n: 'p',
    name: 'param'
};
var objArray = [
    {
        k: 'z',
        key: 'g',
        n: 'a',
        name: 'b'
    },
    {
        k: 'y',
        key: 'h',
        n: 'b',
        name: 't'
    },
    {
        k: 'x',
        key: 'o',
        n: 'a',
        name: 'c'
    }
];
var exp = jux.sort(sortKeys);

console.log('@juxSort Expression:', exp);
console.log('@juxSort:', objArray.sort(function(a, b){
    return eval(exp);
}));

You can also use this function over an iteration for each object to create a better collective expression for all of the keys in each of your objects, and then filter your array that way.

This is a small snippet from the API Juxtapose which I have almost complete, which does this, object equality with exemptions, object unities, and array condensation. If these are things you need or want for your project please comment and I'll make the lib accessible sooner than later.

Hope this helps! Happy coding :)


The most straightforward and readable approach will be the usage of native javascript filter method.

Native javaScript filter takes a declarative approach in filtering array elements. Since it is a method defined on Array.prototype, it iterates on a provided array and invokes a callback on it. This callback, which acts as our filtering function, takes three parameters:

element — the current item in the array being iterated over

index — the index or location of the current element in the array that is being iterated over

array — the original array that the filter method was applied on Let’s use this filter method in an example. Note that the filter can be applied on any sort of array. In this example, we are going to filter an array of objects based on an object property.

An example of filtering an array of objects based on object properties could look something like this:

// Please do not hate me for bashing on pizza and burgers.
// and FYI, I totally made up the healthMetric param :)
let foods = [
  { type: "pizza", healthMetric: 25 },
  { type: "burger", healthMetric: 10 },
  { type: "salad", healthMetric: 60 },
  { type: "apple", healthMetric: 82 }
];
let isHealthy = food => food.healthMetric >= 50;

const result = foods.filter(isHealthy);

console.log(result.map(food => food.type));
// Result: ['salad', 'apple']

To learn more about filtering arrays in functions and yo build your own filtering, check out this article: https://medium.com/better-programming/build-your-own-filter-e88ba0dcbfae


_x000D_
_x000D_
var names = [{_x000D_
        name: "Joe",_x000D_
        age: 20,_x000D_
        email: "[email protected]"_x000D_
    },_x000D_
    {_x000D_
        name: "Mike",_x000D_
        age: 50,_x000D_
        email: "[email protected]"_x000D_
    },_x000D_
    {_x000D_
        name: "Joe",_x000D_
        age: 45,_x000D_
        email: "[email protected]"_x000D_
    }_x000D_
];_x000D_
const res = _.filter(names, (name) => {_x000D_
    return name.name == "Joe" && name.age < 30;_x000D_
_x000D_
});_x000D_
console.log(res);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.js"></script>
_x000D_
_x000D_
_x000D_


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?