Javascript как найти объект в массиве

Use the find() method:

myArray.find(x => x.id === '45').foo;

From MDN:

The find() method returns the first value in the array, if an element in the array satisfies the provided testing function. Otherwise undefined is returned.


If you want to find its index instead, use findIndex():

myArray.findIndex(x => x.id === '45');

From MDN:

The findIndex() method returns the index of the first element in the array that satisfies the provided testing function. Otherwise -1 is returned.


If you want to get an array of matching elements, use the filter() method instead:

myArray.filter(x => x.id === '45');

This will return an array of objects. If you want to get an array of foo properties, you can do this with the map() method:

myArray.filter(x => x.id === '45').map(x => x.foo);

Side note: methods like find() or filter(), and arrow functions are not supported by older browsers (like IE), so if you want to support these browsers, you should transpile your code using Babel (with the polyfill).

user229044's user avatar

user229044

231k40 gold badges328 silver badges336 bronze badges

answered Feb 14, 2016 at 21:11

Michał Perłakowski's user avatar

12

As you are already using jQuery, you can use the grep function which is intended for searching an array:

var result = $.grep(myArray, function(e){ return e.id == id; });

The result is an array with the items found. If you know that the object is always there and that it only occurs once, you can just use result[0].foo to get the value. Otherwise you should check the length of the resulting array. Example:

if (result.length === 0) {
  // no result found
} else if (result.length === 1) {
  // property found, access the foo property using result[0].foo
} else {
  // multiple items found
}

CodeJunkie's user avatar

answered Sep 9, 2011 at 15:54

Guffa's user avatar

GuffaGuffa

684k108 gold badges732 silver badges999 bronze badges

13

Another solution is to create a lookup object:

var lookup = {};
for (var i = 0, len = array.length; i < len; i++) {
    lookup[array[i].id] = array[i];
}

... now you can use lookup[id]...

This is especially interesting if you need to do many lookups.

This won’t need much more memory since the IDs and objects will be shared.

answered Sep 9, 2011 at 15:50

Aaron Digulla's user avatar

Aaron DigullaAaron Digulla

320k108 gold badges595 silver badges816 bronze badges

14

ECMAScript 2015 (JavaScript ES6) provides the find()
method on arrays:

var myArray = [
 {id:1, name:"bob"},
 {id:2, name:"dan"},
 {id:3, name:"barb"},
]

// grab the Array item which matchs the id "2"
var item = myArray.find(item => item.id === 2);

// print
console.log(item.name);

It works without external libraries. But if you want older browser support you might want to include this polyfill.

Henke's user avatar

Henke

4,1673 gold badges31 silver badges40 bronze badges

answered Feb 10, 2014 at 22:32

Rúnar Berg's user avatar

Rúnar BergRúnar Berg

4,1591 gold badge21 silver badges38 bronze badges

7

Underscore.js has a nice method for that:

myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'},etc.]
obj = _.find(myArray, function(obj) { return obj.id == '45' })

answered Nov 22, 2012 at 12:52

GijsjanB's user avatar

GijsjanBGijsjanB

9,9244 gold badges23 silver badges27 bronze badges

3

I think the easiest way would be the following, but it won’t work on Internet Explorer 8 (or earlier):

var result = myArray.filter(function(v) {
    return v.id === '45'; // Filter out the appropriate one
})[0].foo; // Get result and access the foo property

Peter Mortensen's user avatar

answered Sep 9, 2011 at 15:46

pimvdb's user avatar

pimvdbpimvdb

151k77 gold badges306 silver badges352 bronze badges

5

Try the following

function findById(source, id) {
  for (var i = 0; i < source.length; i++) {
    if (source[i].id === id) {
      return source[i];
    }
  }
  throw "Couldn't find object with id: " + id;
}

answered Sep 9, 2011 at 15:45

JaredPar's user avatar

JaredParJaredPar

729k148 gold badges1236 silver badges1452 bronze badges

5

myArray.filter(function(a){ return a.id == some_id_you_want })[0]

answered Apr 16, 2015 at 17:31

Danilo Colasso's user avatar

2

A generic and more flexible version of the findById function above:

// array = [{key:value},{key:value}]
function objectFindByKey(array, key, value) {
    for (var i = 0; i < array.length; i++) {
        if (array[i][key] === value) {
            return array[i];
        }
    }
    return null;
}

var array = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}];
var result_obj = objectFindByKey(array, 'id', '45');

answered Jul 13, 2012 at 20:34

will Farrell's user avatar

will Farrellwill Farrell

1,7051 gold badge16 silver badges21 bronze badges

Performance

Today 2020.06.20 I perform test on MacOs High Sierra on Chrome 81.0, Firefox 77.0 and Safari 13.1 for chosen solutions.

Conclusions for solutions which use precalculations

Solutions with precalculations (K,L) are (much much) faster than other solutions and will not be compared with them — probably they are use some special build-in browser optimisations

  • surprisingly on Chrome and Safari solution based on Map (K) are much faster than solution based on object {} (L)
  • surprisingly on Safari for small arrays solution based on object {} (L) is slower than traditional for (E)
  • surprisingly on Firefox for small arrays solution based on Map (K) is slower than traditional for (E)

Conclusions when searched objects ALWAYS exists

  • solution which use traditional for (E) is fastest for small arrays and fast for big arrays
  • solution using cache (J) is fastest for big arrays — surprisingly for small arrays is medium fast
  • solutions based on find (A) and findIndex (B) are fast for small arras and medium fast on big arrays
  • solution based on $.map (H) is slowest on small arrays
  • solution based on reduce (D) is slowest on big arrays

enter image description here

Conclusions when searched objects NEVER exists

  • solution based on traditional for (E) is fastest on small and big arrays (except Chrome-small arrays where it is second fast)
  • solution based on reduce (D) is slowest on big arrays
  • solution which use cache (J) is medium fast but can be speed up if we save in cache also keys which have null values (which was not done here because we want to avoid unlimited memory consumption in cache in case when many not existing keys will be searched)

enter image description here

Details

For solutions

  • without precalculations: A
    B
    C
    D
    E
    F
    G
    H
    I
    J (the J solution use ‘inner’ cache and it speed depend on how often searched elements will repeat)
  • with precalculations
    K
    L

I perform four tests. In tests I want to find 5 objects in 10 loop iterations (the objects ID not change during iterations) — so I call tested method 50 times but only first 5 times have unique id values:

  • small array (10 elements) and searched object ALWAYS exists — you can perform it HERE
  • big array (10k elements) and searched object ALWAYS exist — you can perform it HERE
  • small array (10 elements) and searched object NEVER exists — you can perform it HERE
  • big array (10k elements) and searched object NEVER exists — you can perform it HERE

Tested codes are presented below

Example tests results for Chrome for small array where searched objects always exists

enter image description here

answered Jun 20, 2020 at 22:52

Kamil Kiełczewski's user avatar

Kamil KiełczewskiKamil Kiełczewski

83.1k29 gold badges359 silver badges335 bronze badges

1

As others have pointed out, .find() is the way to go when looking for one object within your array. However, if your object cannot be found using this method, your program will crash:

const myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}];
const res = myArray.find(x => x.id === '100').foo; // Uh oh!
/*
Error:
"Uncaught TypeError: Cannot read property 'foo' of undefined"
or in newer chrome versions:
Uncaught TypeError: Cannot read properties of undefined (reading 'foo')
*/

This can be fixed by checking whether the result of .find() is defined before using .foo on it. Modern JS allows us to do this easily with optional chaining, returning undefined if the object cannot be found, rather than crashing your code:

const myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}];
const res = myArray.find(x => x.id === '100')?.foo; // No error!
console.log(res); // undefined when the object cannot be found

answered Jun 13, 2020 at 11:20

Nick Parsons's user avatar

Nick ParsonsNick Parsons

44.8k6 gold badges46 silver badges63 bronze badges

If you do this multiple times, you may set up a Map (ES6):

const map = new Map( myArray.map(el => [el.id, el]) );

Then you can simply do a O(1) lookup:

map.get(27).foo

answered Aug 8, 2017 at 15:26

Jonas Wilms's user avatar

Jonas WilmsJonas Wilms

130k20 gold badges144 silver badges150 bronze badges

You can get this easily using the map() function:

myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}];

var found = $.map(myArray, function(val) {
    return val.id == 45 ? val.foo : null;
});

//found[0] == "bar";

Working example: http://jsfiddle.net/hunter/Pxaua/

Peter Mortensen's user avatar

answered Sep 9, 2011 at 15:46

hunter's user avatar

hunterhunter

62.1k19 gold badges113 silver badges113 bronze badges

1

Using native Array.reduce

var array = [ {'id':'73' ,'foo':'bar'} , {'id':'45' ,'foo':'bar'} , ];
var id = 73;
var found = array.reduce(function(a, b){
    return (a.id==id && a) || (b.id == id && b)
});

returns the object element if found, otherwise false

Community's user avatar

answered Jun 4, 2015 at 0:13

laggingreflex's user avatar

laggingreflexlaggingreflex

32.5k35 gold badges140 silver badges195 bronze badges

1

You can use filters,

  function getById(id, myArray) {
    return myArray.filter(function(obj) {
      if(obj.id == id) {
        return obj 
      }
    })[0]
  }

get_my_obj = getById(73, myArray);

answered Sep 13, 2013 at 9:43

Joe Lewis's user avatar

Joe LewisJoe Lewis

1,9402 gold badges17 silver badges18 bronze badges

1

While there are many correct answers here, many of them do not address the fact that this is an unnecessarily expensive operation if done more than once. In an extreme case this could be the cause of real performance problems.

In the real world, if you are processing a lot of items and performance is a concern it’s much faster to initially build a lookup:

var items = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}];

var lookup = items.reduce((o,i)=>o[i.id]=o,{});

you can then get at items in fixed time like this :

var bar = o[id];

You might also consider using a Map instead of an object as the lookup: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Map

answered Mar 23, 2016 at 10:24

Tom's user avatar

TomTom

7,9748 gold badges44 silver badges62 bronze badges

Recently, I have to face the same thing in which I need to search the string from a huge array.

After some search I found It’ll be easy to handle with simple code:

Code:

var items = mydata.filter(function(item){
    return item.word.toLowerCase().startsWith( 'gk );
})

See https://jsfiddle.net/maheshwaghmare/cfx3p40v/4/

Serach from 20k strings

answered Jul 25, 2019 at 10:05

maheshwaghmare's user avatar

0

Iterate over any item in the array. For every item you visit, check that item’s id. If it’s a match, return it.

If you just want teh codez:

function getId(array, id) {
    for (var i = 0, len = array.length; i < len; i++) {
        if (array[i].id === id) {
            return array[i];
        }
    }
    return null; // Nothing found
}

And the same thing using ECMAScript 5’s Array methods:

function getId(array, id) {
    var obj = array.filter(function (val) {
        return val.id === id;
    });

    // Filter returns an array, and we just want the matching item.
    return obj[0];
}

Peter Mortensen's user avatar

answered Sep 9, 2011 at 15:46

Zirak's user avatar

ZirakZirak

38.7k12 gold badges81 silver badges92 bronze badges

You may try out Sugarjs from http://sugarjs.com/.

It has a very sweet method on Arrays, .find. So you can find an element like this:

array.find( {id: 75} );

You may also pass an object with more properties to it to add another «where-clause».

Note that Sugarjs extends native objects, and some people consider this very evil…

Peter Mortensen's user avatar

answered Nov 6, 2012 at 8:52

deepflame's user avatar

deepflamedeepflame

9281 gold badge8 silver badges19 bronze badges

3

As long as the browser supports ECMA-262, 5th edition (December 2009), this should work, almost one-liner:

var bFound = myArray.some(function (obj) {
    return obj.id === 45;
});

Peter Mortensen's user avatar

answered Apr 8, 2014 at 17:14

aggaton's user avatar

aggatonaggaton

2,9922 gold badges23 silver badges36 bronze badges

1

Here’s how I’d go about it in pure JavaScript, in the most minimal manner I can think of that works in ECMAScript 3 or later. It returns as soon as a match is found.

var getKeyValueById = function(array, key, id) {
    var testArray = array.slice(), test;
    while(test = testArray.pop()) {
        if (test.id === id) {
            return test[key];
        }
    }
    // return undefined if no matching id is found in array
    return;
}

var myArray = [{'id':'73', 'foo':'bar'}, {'id':'45', 'foo':'bar'}]
var result = getKeyValueById(myArray, 'foo', '45');

// result is 'bar', obtained from object with id of '45'

answered Feb 28, 2015 at 18:04

Dan W's user avatar

Dan WDan W

7625 silver badges8 bronze badges

More generic and short

function findFromArray(array,key,value) {
        return array.filter(function (element) {
            return element[key] == value;
        }).shift();
}

in your case Ex. var element = findFromArray(myArray,'id',45) that will give you the whole element.

answered Dec 12, 2018 at 6:35

Savan Kaneriya's user avatar

0

We can use Jquery methods $.each()/$.grep()

var data= [];
$.each(array,function(i){if(n !== 5 && i > 4){data.push(item)}}

or

var data = $.grep(array, function( n, i ) {
  return ( n !== 5 && i > 4 );
});

use ES6 syntax:

Array.find, Array.filter, Array.forEach, Array.map

Or use Lodash https://lodash.com/docs/4.17.10#filter, Underscore https://underscorejs.org/#filter

Samuel Liew's user avatar

Samuel Liew

76.1k107 gold badges156 silver badges258 bronze badges

answered Sep 25, 2018 at 6:49

TLbiz's user avatar

TLbizTLbiz

4878 silver badges7 bronze badges

Building on the accepted answer:

jQuery:

var foo = $.grep(myArray, function(e){ return e.id === foo_id})
myArray.pop(foo)

Or CoffeeScript:

foo = $.grep myArray, (e) -> e.id == foo_id
myArray.pop foo

Peter Mortensen's user avatar

answered Oct 23, 2014 at 14:23

stevenspiel's user avatar

stevenspielstevenspiel

5,72513 gold badges60 silver badges89 bronze badges

Use Array.prototype.filter() function.

DEMO: https://jsfiddle.net/sumitridhal/r0cz0w5o/4/

JSON

var jsonObj =[
 {
  "name": "Me",
  "info": {
   "age": "15",
   "favColor": "Green",
   "pets": true
  }
 },
 {
  "name": "Alex",
  "info": {
   "age": "16",
   "favColor": "orange",
   "pets": false
  }
 },
{
  "name": "Kyle",
  "info": {
   "age": "15",
   "favColor": "Blue",
   "pets": false
  }
 }
];

FILTER

var getPerson = function(name){
    return jsonObj.filter(function(obj) {
      return obj.name === name;
    });
}

answered May 2, 2017 at 15:40

Sumit Ridhal's user avatar

Sumit RidhalSumit Ridhal

1,3493 gold badges14 silver badges30 bronze badges

3

You can do this even in pure JavaScript by using the in built «filter» function for arrays:

Array.prototype.filterObjects = function(key, value) {
    return this.filter(function(x) { return x[key] === value; })
}

So now simply pass «id» in place of key and «45» in place of value, and you will get the full object matching an id of 45. So that would be,

myArr.filterObjects("id", "45");

answered Oct 26, 2014 at 4:39

kaizer1v's user avatar

kaizer1vkaizer1v

8988 silver badges20 bronze badges

1

I really liked the answer provided by Aaron Digulla but needed to keep my array of objects so I could iterate through it later. So I modified it to

	var indexer = {};
	for (var i = 0; i < array.length; i++) {
	    indexer[array[i].id] = parseInt(i);
	}
	
	//Then you can access object properties in your array using 
	array[indexer[id]].property

answered Nov 19, 2014 at 3:55

quincyaft's user avatar

1

Use:

var retObj ={};
$.each(ArrayOfObjects, function (index, obj) {

        if (obj.id === '5') { // id.toString() if it is int

            retObj = obj;
            return false;
        }
    });
return retObj;

It should return an object by id.

Peter Mortensen's user avatar

answered Feb 28, 2013 at 15:03

volumexxx's user avatar

2

This solution may helpful as well:

Array.prototype.grep = function (key, value) {
    var that = this, ret = [];
    this.forEach(function (elem, index) {
        if (elem[key] === value) {
            ret.push(that[index]);
        }
    });
    return ret.length < 2 ? ret[0] : ret;
};
var bar = myArray.grep("id","45");

I made it just like $.grep and if one object is find out, function will return the object, rather than an array.

Peter Mortensen's user avatar

answered Oct 22, 2014 at 9:15

soytian's user avatar

soytiansoytian

3182 silver badges3 bronze badges

2

Dynamic cached find

In this solution, when we search for some object, we save it in cache. This is middle point between «always search solutions» and «create hash-map for each object in precalculations».

Community's user avatar

answered Jun 17, 2020 at 23:29

Kamil Kiełczewski's user avatar

Kamil KiełczewskiKamil Kiełczewski

83.1k29 gold badges359 silver badges335 bronze badges

I have an array of objects:

Object = {
   1 : { name : bob , dinner : pizza },
   2 : { name : john , dinner : sushi },
   3 : { name : larry, dinner : hummus }
}

I want to be able to search the object/array for where the key is «dinner», and see if it matches «sushi».

I know jQuery has $.inArray, but it doesn’t seem to work on arrays of objects. Or maybe I’m wrong. indexOf also seems to only work on one array level.

Is there no function or existing code for this?

Heretic Monkey's user avatar

asked Mar 3, 2011 at 13:45

Questioner's user avatar

3

If you have an array such as

var people = [
  { "name": "bob", "dinner": "pizza" },
  { "name": "john", "dinner": "sushi" },
  { "name": "larry", "dinner": "hummus" }
];

You can use the filter method of an Array object:

people.filter(function (person) { return person.dinner == "sushi" });
  // => [{ "name": "john", "dinner": "sushi" }]

In newer JavaScript implementations you can use a function expression:

people.filter(p => p.dinner == "sushi")
  // => [{ "name": "john", "dinner": "sushi" }]

You can search for people who have "dinner": "sushi" using a map

people.map(function (person) {
  if (person.dinner == "sushi") {
    return person
  } else {
    return null
  }
}); // => [null, { "name": "john", "dinner": "sushi" }, null]

or a reduce

people.reduce(function (sushiPeople, person) {
  if (person.dinner == "sushi") {
    return sushiPeople.concat(person);
  } else {
    return sushiPeople
  }
}, []); // => [{ "name": "john", "dinner": "sushi" }]

I’m sure you are able to generalize this to arbitrary keys and values!

answered Mar 3, 2011 at 14:05

ase's user avatar

asease

13.2k4 gold badges34 silver badges46 bronze badges

6

jQuery has a built-in method jQuery.grep that works similarly to the ES5 filter function from @adamse’s Answer and should work fine on older browsers.

Using adamse’s example:

var peoples = [
  { "name": "bob", "dinner": "pizza" },
  { "name": "john", "dinner": "sushi" },
  { "name": "larry", "dinner": "hummus" }
];

you can do the following

jQuery.grep(peoples, function (person) { return person.dinner == "sushi" });
  // => [{ "name": "john", "dinner": "sushi" }]

Community's user avatar

answered Mar 25, 2013 at 18:32

Zach Lysobey's user avatar

Zach LysobeyZach Lysobey

14.7k20 gold badges94 silver badges148 bronze badges

var getKeyByDinner = function(obj, dinner) {
    var returnKey = -1;

    $.each(obj, function(key, info) {
        if (info.dinner == dinner) {
           returnKey = key;
           return false; 
        };   
    });

    return returnKey;       

}

jsFiddle.

So long as -1 isn’t ever a valid key.

answered Mar 3, 2011 at 13:56

alex's user avatar

alexalex

477k200 gold badges876 silver badges980 bronze badges

1

If you’re going to be doing this search frequently, consider changing the format of your object so dinner actually is a key. This is kind of like assigning a primary clustered key in a database table. So, for example:

Obj = { 'pizza' : { 'name' : 'bob' }, 'sushi' : { 'name' : 'john' } }

You can now easily access it like this: Object['sushi']['name']

Or if the object really is this simple (just ‘name’ in the object), you could just change it to:

Obj = { 'pizza' : 'bob', 'sushi' : 'john' }

And then access it like: Object['sushi'].

It’s obviously not always possible or to your advantage to restructure your data object like this, but the point is, sometimes the best answer is to consider whether your data object is structured the best way. Creating a key like this can be faster and create cleaner code.

answered Mar 8, 2013 at 17:12

dallin's user avatar

dallindallin

8,6012 gold badges35 silver badges41 bronze badges

2

You can find the object in array with Alasql library:

var data = [ { name : "bob" , dinner : "pizza" }, { name : "john" , dinner : "sushi" },
     { name : "larry", dinner : "hummus" } ];

var res = alasql('SELECT * FROM ? WHERE dinner="sushi"',[data]);

Try this example in jsFiddle.

answered Dec 21, 2014 at 20:48

agershun's user avatar

agershunagershun

4,06738 silver badges41 bronze badges

2

You can use a simple for in loop:

for (prop in Obj){
    if (Obj[prop]['dinner'] === 'sushi'){

        // Do stuff with found object. E.g. put it into an array:
        arrFoo.push(Obj[prop]);
    }
}

The following fiddle example puts all objects that contain dinner:sushi into an array:

https://jsfiddle.net/3asvkLn6/1/

answered Jul 7, 2015 at 1:10

Rotareti's user avatar

RotaretiRotareti

48.3k21 gold badges111 silver badges106 bronze badges

There’s already a lot of good answers here so why not one more, use a library like lodash or underscore :)

obj = {
   1 : { name : 'bob' , dinner : 'pizza' },
   2 : { name : 'john' , dinner : 'sushi' },
   3 : { name : 'larry', dinner : 'hummus' }
}

_.where(obj, {dinner: 'pizza'})
>> [{"name":"bob","dinner":"pizza"}]

answered Jul 30, 2015 at 1:19

TomDotTom's user avatar

TomDotTomTomDotTom

6,1603 gold badges40 silver badges39 bronze badges

I had to search a nested sitemap structure for the first leaf item that machtes a given path. I came up with the following code just using .map() .filter() and .reduce. Returns the last item found that matches the path /c.

var sitemap = {
  nodes: [
    {
      items: [{ path: "/a" }, { path: "/b" }]
    },
    {
      items: [{ path: "/c" }, { path: "/d" }]
    },
    {
      items: [{ path: "/c" }, { path: "/d" }]
    }
  ]
};

const item = sitemap.nodes
  .map(n => n.items.filter(i => i.path === "/c"))
  .reduce((last, now) => last.concat(now))
  .reduce((last, now) => now);

Edit 4n4904z07

answered Oct 18, 2018 at 11:58

Marc's user avatar

MarcMarc

4,6653 gold badges27 silver badges34 bronze badges

If You want to find a specific object via search function just try something like this:

    function findArray(value){

        let countLayer = dataLayer.length;
        for(var x = 0 ; x < countLayer ; x++){

            if(dataLayer[x].user){
                let newArr = dataLayer[x].user;
                let data = newArr[value];
                return data;
            }

        }

        return null;

    }

    findArray("id");

This is an example object:

layerObj = {
    0: { gtm.start :1232542, event: "gtm.js"},
    1: { event: "gtm.dom", gtm.uniqueEventId: 52},
    2: { visitor id: "abcdef2345"},
    3: { user: { id: "29857239", verified: "Null", user_profile: "Personal", billing_subscription: "True", partners_user: "adobe"}
}

Code will iterate and find the «user» array and will search for the object You seek inside.

My problem was when the array index changed every window refresh and it was either in 3rd or second array, but it does not matter.

Worked like a charm for Me!

In Your example it is a bit shorter:

function findArray(value){

    let countLayer = Object.length;
    for(var x = 0 ; x < countLayer ; x++){

        if(Object[x].dinner === value){
            return Object[x];
        }

    }

    return null;

}

findArray('sushi');

answered Feb 24, 2020 at 14:00

z3r0's user avatar

z3r0z3r0

397 bronze badges

We use object-scan for most of our data processing. It’s conceptually very simple, but allows for a lot of cool stuff. Here is how you would solve your question

// const objectScan = require('object-scan');

const findDinner = (dinner, data) => objectScan(['*'], {
  abort: true,
  rtn: 'value',
  filterFn: ({ value }) => value.dinner === dinner
})(data);

const data = { 1: { name: 'bob', dinner: 'pizza' }, 2: { name: 'john', dinner: 'sushi' }, 3: { name: 'larry', dinner: 'hummus' } };

console.log(findDinner('sushi', data));
// => { name: 'john', dinner: 'sushi' }
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/object-scan@13.8.0"></script>

Disclaimer: I’m the author of object-scan

answered Oct 7, 2019 at 4:13

vincent's user avatar

vincentvincent

1,8833 gold badges17 silver badges24 bronze badges

  • Главная

  • Инструкции

  • JavaScript

  • Методы поиска в массивах JavaScript

Blog

Поиск в массиве — довольно несложная задача для программиста. На ум сразу приходит перебор через цикл for или бинарный поиск в отсортированном массиве, для элементов которого определены операции «больше» и «меньше». Но, как и любой высокоуровневый язык программирования, JavaScript предлагает разработчику встроенные функции для решения различных задач. В этой статье мы рассмотрим четыре метода поиска в массивах JavaScript: find, includes, indexOf и filter.

Методы Поиска В Массивах Java Script (1)

indexOf

indexOf — это функция поиска элемента в массиве. Этот метод с помощью перебора ищет искомый объект и возвращает его индекс или «-1», если не находит подходящий.

Синтаксис

Функция имеет такой синтаксис:

Array.indexOf (search element, starting index)

где:

  • Array — массив;
  • search element — элемент, который мы ищем;
  • starting index — индекс, с которого начинаем перебор. Необязательный аргумент, по умолчанию работа функции начинается с индекса “0”, т.е. метод проверяет весь Array. Если starting index больше или равен Array.length, то метод сразу возвращает “-1” и завершает работу. 

Если starting index отрицательный, то JS трактует это как смещение с конца  массива: при starting index = “-1” будет проверен только последний элемент, при “-2” последние два и т.д. 

Практика

Опробуем метод на практике. Запустим такой код и проверим результаты его работы:

let ExampleArray = [1,2,3,1,'5', null, false, NaN,3];

console.log("Позиция единицы", ExampleArray.indexOf(1) );
console.log("Позиция следующей единицы", ExampleArray.indexOf(1,2) );
console.log("Позиция тройки", ExampleArray.indexOf(3) );
console.log("Позиция тройки, если starting index отрицательный", ExampleArray.indexOf(3,-2) );
console.log("Позиция false", ExampleArray.indexOf(false) );
console.log("Позиция 5", ExampleArray.indexOf("5") ); 
console.log("Позиция NaN", ExampleArray.indexOf(NaN));

В результате работы этого кода мы получили такой вывод: 

Позиция единицы 0
Позиция следующей единицы 3
Позиция тройки 2
Позиция тройки, если starting index отрицательный 8
Позиция false 6
Позиция 5 -1
Позиция NaN -1

indexOf осуществляет поиск элемента в массиве слева направо и останавливает свою работу на первом совпавшем. Отчетливо это проявляется в примере с единицей. Для того, чтобы идти справа налево, используйте метод LastIndexOf с аналогичным синтаксисом.

Для сравнения искомого и очередного объекта применяется строгое сравнение (===). При использовании строгого сравнения для разных типов данных, но с одинаковым значение, например 5, ‘5’ и “5” JavaScript даёт отрицательный результат, поэтому IndexOf не нашел 5. 

Также стоит помнить, что indexOf некорректно обрабатывает NaN. Так что для работы с этим значением нужно применять остальные методы.

includes

includes не совсем проводит поиск заданного элемента в массиве, а проверяет, есть ли он там вообще. Работает он примерно также как и indexOf. В конце работы includes возвращает «True», если нашел искомый объект, и «False», если нет. Также includes правильно обрабатывает NaN

Синтаксис

includes имеет следующий синтаксис:

Array.includes (search element, starting index)

где: 

  • Array — массив;
  • search element — элемент, который мы ищем;
  • starting index — индекс, с которого начинаем перебор. Необязательный аргумент, по умолчанию работа функции начинается с индекса “0”, т.е. метод проверяет весь Array. Если starting index больше или равен Array.length, то метод сразу возвращает «False» и завершает работу.  

Если starting index отрицательный, то JS трактует это как смещение с конца массива: при starting index = “-1” будет проверен только последний элемент, при “-2” последние два и т.д.  

Практика

Немного изменим код из предыдущего примера и запустим его:

let Example = [1,2,3,1,'5', null, false,NaN, 3];

console.log("Наличие единицы", Example.includes(1) );
console.log("Наличие следующей единицы", Example.includes(1,2) );
console.log("Наличие тройки", Example.includes(3) );
console.log("Наличие тройки, если starting index отрицательный", Example.includes(3,-1) );
console.log("Наличие false", Example.includes(false) );
console.log("Наличие 5", Example.includes(5) ); 
console.log("Наличие NaN", Example.includes(NaN));

Вывод:

Наличие единицы true
Наличие следующей единицы true
Наличие тройки true
Наличие тройки, если starting index отрицательный true
Наличие false true
Наличие 5 false
Наличие NaN true

Для includes отсутствует альтернативная функция, которая проводит поиск по массиву js справа налево, которая, в общем-то, и не очень актуальна.

find

Предположим, что нам нужно найти в массиве некий объект. Но мы хотим найти его не по значению, а по его свойству. Например, поиск числа в массиве со значением между 15 и 20. Как и прежде, мы можем воспользоваться перебором с помощью for, но это не слишком удобно. Для поиска с определенным условием в JavaScript существует метод find.

Синтаксис

Array.find(function(...){
//если элемент соответствует условиям (true), то функция возвращает его  и прекращает работу;
//если ничего не найдено, то возвращает undefined
})
  • Array — массив;
  • function(…) — функция, которая задает условия.

Практика

Как и в прошлых примерах, напишем небольшой код и опробуем метод:

let ExampleArray = ["Timeweb", 55555, "Cloud", "облачный провайдер", "буквы"];

console.log(ExampleArray.find(element => element.length == 5))

Вывод:

Cloud

В этом примере мы искали строки с длиной в 5 символов. Для числовых типов данных длина не определена, поэтому 55555 не подходит. find находит первый элемент и возвращает его, поэтому «буквы» также не попали в результат работы нашей функции. Для того, чтобы найти несколько элементов, соответствующих некоторому условию, нужно использовать метод filter.

Также не стоит забывать о методе findIndex. Он возвращает индекс подходящего элемента. Или -1, если его нет. В остальном он работает точно также, как и find.

filter

find ищет и возвращает первый попавшийся элемент, соответствующий условиям поиска. Для того, чтобы найти все такие элементы, необходимо использовать метод filter. Результат этой функции — массив (если ничего не найдено, то он будет пустым).

Синтаксис

Array.find(function(...){
//если элемент соответствует условиям (true), то добавляем его к конечному результату и продолжаем перебор;
})
  • Array — массив;
  • function(…) — функция, которая задает условия.

Практика

Представим следующую задачу: у нас есть список кубоидов (прямоугольных параллелепипедов) с длинами их граней и нам нужно вывести все кубоиды с определенным объемом. Напишем код, реализующий решение данной задачи:

let ExampleArray = [
  [10, 15, 8],
  [11, 12, 6],
  [5, 20, 1],
  [10, 10, 2],
  [16,2, 4]
  ];

console.log(ExampleArray.filter(element=> element[0]*element[1]*element[2]>300))

 Вывод:

[ [ 10, 15, 8 ],
 [ 11, 12, 6 ] ]

В этом примере мы нашли прямоугольные параллелепипеды с объемом больше 300. В целом, метод filter в JS позволяет реализовывать всевозможные условия для поиска. 

Заключение

В этой статье узнали о методах поиска в JavaScript и научились ими пользоваться. Все перечисленные методы — универсальные инструменты для разработчиков. Но, как и любые универсальные инструменты, они не всегда являются самыми производительными. Так, например, бинарный поиск будет куда эффективнее, чем find и filter.

In this article, we will learn how to search and find an object in an array of objects based on particular criteria. First, we will discuss different ways in which we can find an object in an array and then move on to the different criteria through which we can search for the object.

Let’s consider an example of an array of car objects with properties of id, brand, model, price, and release_date with id having the unique value for every object.

car_list

List of cars, source: pinterest.com
const carList = [{ id:13, brand: "BMW", model: "X5", price:"$23000", release_date:"2015-10-12"},

                 { id:9, brand: "Audi", model: "S3", price:"$35000", release_date:"2013-08-23"},

                 { id:11, brand: "Bugatti", model: "Veyron", price:"$500000", release_date:"2006-02-10"},
                 
                 { id:7, brand: "VW", model: "Polo", price:"$8000", release_date:"2018-05-03"},
                
                 { id:4, brand: "Fiat", model: "Punto", price:"$6000", release_date:"2017-01-25"}]

There are two approaches to find the required object, they are as follows:

  1. Finding index of search object using Array.findIndex()
  2. Searching the object directly using Array.find()

Method 1: Array.findIndex() to find the search index

The first approach would be to find the array index of the search object using Array.findIndex(). Once the search index is found, we can access the search object by “array[index]” and then perform any required operations on the object that is found. This method is useful when we need to update the search object reference of the array.

In the below example, we find the index of the object with model value as “X5” and print the price and brand through the “carList[searchIndex]” object reference. Read more about Array.findIndex() from developer.mozilla.org/Array/findIndex.

// Finding index of the car with modal "X5" 
const searchIndex = carList.findIndex((car) => car.model=="X5");

console.log(`Model X5 is present in brand ${carList[searchIndex].brand}`);
//"Model X5 is present in brand BMW"

console.log(`The price of model X5 is ${carList[searchIndex].price}`);
//"The price of model X5 is $23000"

Method 2: Array.find() to find the search object

Another approach would be to find the search object itself by using Array.find() and assign it to a variable. Now all the search object details can be accessed from this variable. This approach is more suitable if we want to perform operations on search objects independently from the array.

In the below example, we find the object entry with model value as “X5” from the array using Array.find() and print its brand and price values. Read more about Array.find() from developer.mozilla.org/Array/find.

// Finding car object with modal "X5" 
const searchObject= carList.find((car) => car.model=="X5");

console.log(`Model X5 is present in brand ${searchObject.brand}`);
//"Model X5 is present in brand BMW"

console.log(`The price of model X5 is ${searchObject.price}`);
//"The price of model X5 is $23000"

We need criteria to search the object in the array of objects, here we will discuss 3 types of search that are as follows:

  1. Search object by unique id / Property value
  2. Search object with Min & Max property value
  3. Search object with Latest or oldest date

Find object by Unique id / Property value

The most common approach is to match the search object by unique id or property value, however, it would fail if two or more items have the same value. Simple “==” operator coupled with Array.find() will achieve a successful search operation.

In the below example, carList has a property of “id” which is unique to every object in the array. We find the car object with id = 11 from the array and print the details of the object found.

const searchId = 11;

// Finding car object with id 11
const searchObject = carList.find((car) => car.id == searchId);

const {brand, model, price} = searchObject;

console.log(`Car with id ${searchId} is ${brand} ${model}`);
//"Car with id 11 is Bugatti Veyron"

console.log(`${brand} ${model} is priced at ${price}`);
//"Bugatti Veyron is priced at $500000"

Find object with Min & Max value in array

We can find objects with minimum and maximum values in an array of objects in 3 steps:

  1. Create array of property values using Array.map((item) => item.property)
  2. Find min / max value from the array using Math.max.apply(null, array) or Math.min.apply(null, array)
  3. Find the object with max/ min value using Array.find((item) => item.property == max_value/min_Value)

In the below example, we are finding the most expensive and cheapest car object from carList array.

// Creating array with all prices in number
const prices = carList.map((car) => Number(car.price.replace("$", "")))

// Calculate higest and lowest price value
const highestPrice = "$" + Math.max.apply(null, prices);
const lowestPrice = "$" + Math.min.apply(null, prices);

// Matching values to find the expensive and cheap car
const expensiveCar = carList.find((car) => car.price == highestPrice)
const cheapCar = carList.find((car) => car.price == lowestPrice)

console.log(`Most expensive Car is ${expensiveCar.brand} ${expensiveCar.model} at ${highestPrice}`)
// "Most expensive Car is Bugatti Veyron at $500000"

console.log(`Cheapest Car is ${cheapCar.brand} ${cheapCar.model} at ${lowestPrice}`)
// "Cheapest Car is Fiat Punto at $6000"

Based on Latest or Oldest Date

We need to follow 4 steps to find an object with a min/max date from the array of objects:

  1. Make sure the date field of objects are in YYYY-MM-DD format.
  2. Define callback function for max value which returns Date.parse(car1.release_date) < (Date.parse(car2.release_date) ? a : b
  3. Callback function for min value with Date.parse(car1.release_date) > (Date.parse(car2.release_date) ? a : b
  4. Apply Array.reduce() with the callback function and assign the return value to a variable

In the below example, we find cars with the oldest and latest release date from carList array based on the “release_date” property value.

// "Get car with oldest release date"
const oldestCar = carList.reduce((car1, car2) => {
  return (Date.parse(car1.release_date)) < (Date.parse(car2.release_date)) ? a : b;
});

console.log(`The Oldest Car is ${oldestCar.brand} ${oldestCar.model} at ${oldestCar.release_date}`)
// "The Oldest Car is Bugatti Veyron at 2006-02-10"

// "Get car with latest release date"
const latestCar = carList.reduce((car1, car2) => {
  return (Date.parse(car1.release_date)) > (Date.parse(car2.release_date)) ? a : b;
});

console.log(`The Latest Car is ${latestCar.brand} ${latestCar.model} at ${latestCar.release_date}`)
//"The Latest Car is VW Polo at 2018-05-03"

В этом посте мы обсудим, как определить, содержит ли массив объект с заданным атрибутом в JavaScript.

1. Использование some() метод

Рекомендуемое решение — использовать some() метод, возвращающий true, если в массиве найден хотя бы один объект, удовлетворяющий заданному условию, и false в противном случае.

Следующий пример демонстрирует это, находя человека, живущего в штате NYC.

const people = [

    { name : ‘Jane Smith’, city : ‘New York City’, state : ‘NYC’, zip : ‘10001’ },

    { name : ‘Bob Brown’, city : ‘Colorado’, state : ‘CO’, zip : ‘80011’ },

    { name : ‘Alice Brown’, city : ‘Michigan’, state : ‘MI’, zip : ‘48002’ }

];

const isPresent = people.some(e => e.state === ‘NYC’);

console.log(isPresent);

/*

    результат: true

*/

Скачать  Выполнить код

2. Использование find() метод

Другим решением является использование find() метод, который возвращает первый экземпляр объекта в массиве, который удовлетворяет данному тесту или undefined если он не найден.

const people = [

    { name : ‘Jane Smith’, city : ‘New York City’, state : ‘NYC’, zip : ‘10001’ },

    { name : ‘Bob Brown’, city : ‘Colorado’, state : ‘CO’, zip : ‘80011’ },

    { name : ‘Alice Brown’, city : ‘Michigan’, state : ‘MI’, zip : ‘48002’ }

];

const isPresent = people.find(e => e.state === ‘NYC’) !== undefined;

console.log(isPresent);

/*

    результат: true

*/

Скачать  Выполнить код

3. Использование findIndex() метод

В качестве альтернативы вы можете использовать findIndex() метод, аналогичный методу find() метод, за исключением того, что он возвращает индекс первого экземпляра объекта или -1 если объект не найден.

const people = [

    { name : ‘Jane Smith’, city : ‘New York City’, state : ‘NYC’, zip : ‘10001’ },

    { name : ‘Bob Brown’, city : ‘Colorado’, state : ‘CO’, zip : ‘80011’ },

    { name : ‘Alice Brown’, city : ‘Michigan’, state : ‘MI’, zip : ‘48002’ }

];

const isPresent = people.findIndex(e => e.state === ‘NYC’) !== 1;

console.log(isPresent);

/*

    результат: true

*/

Скачать  Выполнить код

4. Использование filter() метод

Другой вероятный способ — отфильтровать массив, чтобы вернуть все объекты, соответствующие заданному условию. Это можно легко сделать с помощью filter() метод.

const people = [

    { name : ‘Jane Smith’, city : ‘New York City’, state : ‘NYC’, zip : ‘10001’ },

    { name : ‘Bob Brown’, city : ‘Colorado’, state : ‘CO’, zip : ‘80011’ },

    { name : ‘Alice Brown’, city : ‘Michigan’, state : ‘MI’, zip : ‘48002’ }

];

const isPresent = people.filter(e => e.state === ‘NYC’).length > 0;

console.log(isPresent);

/*

    результат: true

*/

Скачать  Выполнить код

5. Использование forEach() метод

Наконец, вы можете выполнить итерацию по массиву, используя forEach() метод и проверьте наличие объекта в массиве.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

const people = [

    { name : ‘Jane Smith’, city : ‘New York City’, state : ‘NYC’, zip : ‘10001’ },

    { name : ‘Bob Brown’, city : ‘Colorado’, state : ‘CO’, zip : ‘80011’ },

    { name : ‘Alice Brown’, city : ‘Michigan’, state : ‘MI’, zip : ‘48002’ }

];

var isPresent = false;

people.forEach(o => {

    if (e => e.state === ‘NYC’) {

        isPresent = true;

    }

});

console.log(isPresent);

/*

    результат: true

*/

Скачать  Выполнить код

Это все о проверке, содержит ли массив объект с заданным атрибутом в JavaScript.

Понравилась статья? Поделить с друзьями:
  • Почему гта запускается в оконном режиме как исправить
  • Как составить письмо для предоставления юридического адреса
  • Как найти файл в народ
  • Как найти длину проекции вектора на вектор
  • Как найти маленькое основание равнобедренной трапеции