How to select all other values in an array except the ith element?

You can use ECMAScript 5 Array.prototype.filter:

var items = [1, 2, 3, 4, 5, 6];
var current = 2;

var itemsWithoutCurrent = items.filter(function(x) { return x !== current; });

There can be any comparison logics instead of x !== current. For example, you can compare object properties.

If you work with primitives, you can also create a custom function like except which will introduce this functionality:

Array.prototype.except = function(val) {
    return this.filter(function(x) { return x !== val; });        
}; 

// Usage example:
console.log([1, 2, 3, 4, 5, 6].except(2)); // 1, 3, 4, 5, 6

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)