Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there any jquery features to query multi-dimensional arrays in a similar fashion to the DOM?

What the question says...

Does jQuery have any methods that will allow you to query a mult-dimensional array of objects in a similar fashion as it does with the DOM.

So for instance, get me a list of objects contained within a multi-dimensional array having some matching property value - for instance where StartOfPeriod greater than a specified date or where name == "Ben Alabaster"

I'd like to avoid re-inventing the wheel if there's something already out there.

like image 484
BenAlabaster Avatar asked Jul 07 '10 00:07

BenAlabaster


People also ask

Does JavaScript support multidimensional array?

Javascript has no inbuilt support for multidimensional arrays, however the language is flexible enough that you can emulate this behaviour easily by populating your arrays with separate arrays, creating a multi-level structure.

Can we use foreach in jQuery?

Learn how to loop through elements, arrays and objects with jQuery using the $. each() function, jQuery's foreach equivalent. jQuery's foreach equivalent can be very useful for many situations. These examples will get you started and teach you how you can loop through arrays, objects and all kinds of HTML elements.

What is multidimensional array in JavaScript?

A multidimensional array is an array that contains another array. For example, // multidimensional array const data = [[1, 2, 3], [1, 3, 4], [4, 5, 6]];

How do you iterate through an array in jQuery?

The $. each() function can be used to iterate over any collection, whether it is an object or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time.


1 Answers

You can't use selector syntax, but jQuery comes with $.grep and $.inArray, which can be useful for this. grep returns a new array of elements that match a predicate. inArray returns the index of the first matching element, or -1. For instance:

var matches = $.grep(array, function(el){
  return el.StartOfPeriod > 2000;
});

These are similar to the standard ECMAScript methods, Array.filter (simimlar to grep) and Array.indexOf (similar to inArray); jQuery actually uses Array.indexOf where available. There are also other useful ECMAScript methods, such as Array.every (all elements matching) and Array.some (at least one matching). MDC has code you can add to your project so these work in browsers that don't have native implementations.

like image 175
Matthew Flaschen Avatar answered Oct 17 '22 08:10

Matthew Flaschen