1

I have this code:

var app = {
    items: [
        [{
            title: 'Overview',
            id: 'dashboard'
        }, {
            title: 'Reports',
            id: 'reports'
        }],
        [{
            title: 'Customers',
            id: 'customers'
        }, {
            title: 'Quotes',
            id: 'quotes'
        }, {
            title: 'Sales',
            id: 'sales'
        }],
        [{
            title: 'Suppliers',
            id: 'suppliers'
        }, {
            title: 'Purchases',
            id: 'purchases'
        }],
        [{
            title: 'Bank',
            id: 'bank'
        }, {
            title: 'Projects',
            id: 'projects',
            disabled: true
        }, {
            title: 'Journal',
            id: 'journal',
            disabled: true
        }]
    ]
}

var userDetails = {
    IsAdmin: true
};

for (var x = 0; x < app.items.length; x++) {
    app.items[x].filter(function (items) {
        if (items.disabled || (userDetails.IsAdmin && items.id !== 'quotes')) {
            var ind = app.items[x].indexOf(items);
            app.items[x].splice(ind, 1);
        }
    });
}

console.log(app.items);

The output is that there is 1 object left in each array by the end. This is not desired, by my calculations, there should just be a single object left (the quotes object),

related jsFiddle: http://jsfiddle.net/UdzEW/

Any ideas?

3
  • 1
    do not modify your array inside the filter callback. Commented Apr 11, 2013 at 11:19
  • 1
    You're misusing the .filter() method Commented Apr 11, 2013 at 11:20
  • It's important to remember that filter is not supported by older browsers, generally speaking. Commented Apr 11, 2013 at 11:43

2 Answers 2

3

The idea of .filter is that you supply a function tahat returns a boolean value which determines whether the value should stay or go; it shouldn't modify the array in-place.

var filtered = app.items[x].filter(function (items) {
    if (items.disabled || (userDetails.IsAdmin && items.id !== 'quotes')) {
        return false;
    }
    return true;
});

The contents of filtered should now contain a new array with only those items that fail the inner condition.

Sign up to request clarification or add additional context in comments.

Comments

0

try this:

 for (var x = 0; x < app.items.length; x++) {
    app.items[x] = app.items[x].filter(function (items) {
       return !(items.disabled || (userDetails.IsAdmin && items.id !== 'quotes'));
   });
   !app.items[x].length && app.items.splice(x--, 1);
 }

it returns [[Array(1)]] with the "Quotes" object

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.