44

I have a function using an array value represented as

 markers[i]

How can I select all other values in an array except this one?

The purpose of this is to reset all other Google Maps images to their original state but highlight a new one by changing the image.

8 Answers 8

29

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
2
  • 6
    This would behave differently if array values are all same i.e. [2, 2, 2, 2] Commented Jun 6, 2017 at 17:06
  • 4
    This removes elements with the value of 2 not the element at ith position Commented Mar 30, 2020 at 13:41
28

Use Array​.prototype​.splice to get an array of elements excluding this one.

This affects the array permanently, so if you don't want that, create a copy first.

var origArray = [0,1,2,3,4,5];
var cloneArray = origArray.slice();
var i = 3;

cloneArray.splice(i,1);

console.log(cloneArray.join("---"));
5
  • @JackDamery yes it will, so you will need to create a copy. Commented Mar 12, 2013 at 12:33
  • @DhruvPathak Bah, no. slice() creates new object, doesn't affect original array at all. The only functions having data impact here are join() and splice(), but they are called after slice().
    – TN888
    Commented Dec 29, 2016 at 0:58
  • @Ty221 My comment was regarding splice, hence created a copy using slice before doing a splice, so that splice doesn't affect the original array. Commented Dec 29, 2016 at 6:43
  • 1
    Link to documentation on slice()
    – Alex Klaus
    Commented Nov 30, 2017 at 1:18
  • good solution, the only caveat is that it won't work with nested loops. If you have a nested loop splice will modify the array and you nested index value will be off
    – newshorts
    Commented May 30, 2021 at 23:31
15

You can also use the second callback parameter in Filter:

const exceptIndex = 3;
const items = ['item1', 'item2', 'item3', 'item4', 'item5'];
const filteredItems = items.filter((value, index) => exceptIndex !== index);
5

You can use slice() Method

var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(1,3);

The slice() method returns the selected elements in an array, as a new array object.

2
  • Definitely the best way! +1
    – xechelonx
    Commented Apr 2, 2017 at 12:47
  • 1
    You would need to call slice more than once and combine the sliced arrays if the item you want to remove is not the first or the last element. To remove element at fruits[x]: const result = [...fruits.slice(1,x-1), ...fruits.slice(x+1, fruits.length)] Commented Mar 30, 2020 at 13:52
2

Another way this can be done is by using filter and slice Array methods.

let array = [ 1, 2, 3, 4, 5, 6 ];
let leave = 2;

// method 1
console.log(array.filter((e,i) => i !== leave));
// logs [1, 2, 4, 5, 6];

//method 2
console.log([...array.slice(0, leave), ...array.slice(leave+1, array.length)]);
// logs [1, 2, 4, 5, 6];
1

This function will return a new array with all elements except the element at the specified index:

    const everythingBut = (array, i) => { /*takes an array and an index as arguments*/
        let notIArray = []; /*creates new empty array*/
        let beforeI = array.slice(0, i); /*creates subarray of all elements before array[i]*/
        let afterI = array.slice(i+1,); /*creates subarray of all elements after array[i]*/
        notIArray = [...beforeI, ...afterI]; /*add elements before and after array[i] to empty array*/
        return notIArray; /*returns new array with array[i] element excluded*/
    };

For example:

    let array = [1, 2, 4, 7, 9, 11, 2, 6]
    everythingBut(array, 2); /*exclude array[2]*/
    // -> [1, 2, 7, 9, 11, 2, 6]
0

You can combine Array.prototype.slice() and Array.prototype.concat() in using startingArray.slice(desiredStartIndex, exclusionIndex).concat(startingArray.slice(exclusionIndex+1)) to exclude the item whose index is exclusionIndex. E.g., if you have a startingArray of [0, 1, 2] and want a desiredArray of [0, 2], then you can do as follows:

startingArray = [0, 1, 2];
desiredStartIndex = 0;
exclusionIndex = 1;
desiredEndIndex = 2;
desiredArray = startingArray.slice(desiredStartIndex, 
exclusionIndex).concat(startingArray.slice(exclusionIndex+1));
-1

With ECMAScript 5

const array = ['a', 'b', 'c'];
const removeAt = 1;
const newArray = [...array].splice(removeAt, 1);
1
  • 2
    [...array].splice(removeAt, 1); returns the removed element Commented May 12, 2020 at 17:01

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.