0

I am looking for a way to filter my JavaScript Array() columns where the parentId is equal to a variable passed into the method.

// Array decleration
var columns = []; // Columns
//...
for (var i1 in columns) {
  if (columns[i1].parentId == listItem) {
  //...

Could anybody recommend the easiest way to filter this using either plain JavaScript or jQuery to avoid using the if statement as shown above?

1

3 Answers 3

5
var filteredColumns = columns.filter(function(column) {
    return column.parentId == listItem;
});
Sign up to request clarification or add additional context in comments.

5 Comments

Sometimes, the user might need some info about the indices of the elements as well. Is there any pure JS equivalent of jQuery grep?
@Cupidvogel: if you check the callback signature you'll find the index in the second argument
The callback takes only one argument here, column, right?
@Cupidvogel: it's not. Please check documentation first for RTFM-alike questions. Thank you.
@Cupidvogel: Relevant section from the documentation: "callback is invoked with three arguments: (1) the value of the element, (2) the index of the element, (3) the Array object being traversed"
2
array = [1,2,3,4,5];
result = $.grep(array, function(n,i) {
   return n > 3;
});

This will return an array of filtered elements where the results are greater than 3. Here n is the element in consideration, and i the index of the element. So as per your requirement, the code can run like this:

resultArray = $.grep(columns,function(n,i) {
   return n == parentId;
});

Comments

1

Use ES5 Array's filter method:

var filtered = columns.filter(function (item) {
  return item.parentId === listItem
});

In the link above there is also a shim for old browsers.

You can also doing that manually:

var filtered = [];

for (var i = 0, item; item = columns[i++];)
  if (item.parentId === listItem) filtered.push(item);

Don't use for…in to iterate over Array.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.