2

Is it possible to filter a javascript array? I've taken the following approach but it doesn't seem to produce the intended results.

Arrays:

var catalog1 = [0]
var catalog2 = [1]
var products = [{ id: "PRODUCTA", desc: "Toys" },
                { id: "PRODUCTB", desc: "Cars" }]

Filter:

var NewProducts = [];
for (r in catalog1) NewProducts.push(products[r]);

NewProducts should contain either product A or B depending on which catalog array is selected. My attempt always return product A, as in r = 0. What am I missing?

http://jsfiddle.net/rE52f/

3
  • In the code you've posted, you're always processing catalog1. Commented Nov 29, 2013 at 17:25
  • @TedHopp yes, I simplified it but in my code there a condition which sets the catalog. In the fiddle, you can see that if you use catalog2, it returns product A, not B. Commented Nov 29, 2013 at 17:27
  • 1
    for (r in catalog1) is not the correct way to iterate over an array. Commented Nov 29, 2013 at 17:33

2 Answers 2

4

It is because Javascript's for each loop generates the keys of your collection. You will have to change it to:

for (var r in someCatalogue) NewProducts.push(products[someCatalogue[r]]);

You can also use map inside a closure, if you don't have to support IE8 and less:

(function(products) {
  NewProducts = someCatalogue.map(function(item) { return products[item]; });
})(products);
Sign up to request clarification or add additional context in comments.

Comments

2

It is possible to filter a JavaScript array, just use the filter method:

var arr = [1, 2, 3, 4, 5, 6];
var result = arr.filter(function(item) {
        return item > 3;
    }
);

In your situation you are trying to filter the products array to include certain elements, so to do it the right way:

var catalog1 = [0];
var catalog2 = [1];
var products = [{ id: "PRODUCTA", desc: "Toys" },
            { id: "PRODUCTB", desc: "Cars" }];

var NewProducts = products.filter( function(item) {
        // check item and if it is accepted then include it.
    }
);

In your code, you are using for/in to loop the array elements which is not the right way to walk the array, use a regular for loop:

var NewProducts = [];
for (var i=0; i<catalog1.length; i++) NewProducts.push(products[catalog1[i]]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.