Remove array in array javascript

I am looking for an efficient way to remove all elements from a javascript array if they are present in another array.

// If I have this array:
var myArray = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];

// and this one:
var toRemove = ['b', 'c', 'g'];

I want to operate on myArray to leave it in this state: ['a', 'd', 'e', 'f']

With jQuery, I'm using grep() and inArray(), which works well:

myArray = $.grep(myArray, function(value) {
    return $.inArray(value, toRemove) < 0;
});

Is there a pure javascript way to do this without looping and splicing?

Remove array in array javascript

Ivar

5,64212 gold badges51 silver badges57 bronze badges

asked Nov 13, 2013 at 15:13

Remove array in array javascript

6

Use the Array.filter() method:

myArray = myArray.filter( function( el ) {
  return toRemove.indexOf( el ) < 0;
} );

Small improvement, as browser support for Array.includes() has increased:

myArray = myArray.filter( function( el ) {
  return !toRemove.includes( el );
} );

Next adaptation using arrow functions:

myArray = myArray.filter( ( el ) => !toRemove.includes( el ) );

answered Nov 13, 2013 at 15:16

SirkoSirko

70.6k19 gold badges143 silver badges175 bronze badges

16

ECMAScript 6 sets can permit faster computing of the elements of one array that aren't in the other:

const myArray = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
const toRemove = new Set(['b', 'c', 'g']);

const difference = myArray.filter( x => !toRemove.has(x) );

console.log(difference); // ["a", "d", "e", "f"]

Since the lookup complexity for the V8 engine browsers use these days is O(1), the time complexity of the whole algorithm is O(n).

JohnK

6,4096 gold badges46 silver badges71 bronze badges

answered May 26, 2017 at 14:35

Benny NeugebauerBenny Neugebauer

47.8k23 gold badges225 silver badges193 bronze badges

2

var myArray = [
  {name: 'deepak', place: 'bangalore'}, 
  {name: 'chirag', place: 'bangalore'}, 
  {name: 'alok', place: 'berhampur'}, 
  {name: 'chandan', place: 'mumbai'}
];
var toRemove = [
  {name: 'deepak', place: 'bangalore'},
  {name: 'alok', place: 'berhampur'}
];



myArray = myArray.filter(ar => !toRemove.find(rm => (rm.name === ar.name && ar.place === rm.place) ))

Remove array in array javascript

answered Apr 29, 2019 at 9:45

5

The filter method should do the trick:

const myArray = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
const toRemove = ['b', 'c', 'g'];

// ES5 syntax
const filteredArray = myArray.filter(function(x) { 
  return toRemove.indexOf(x) < 0;
});

If your toRemove array is large, this sort of lookup pattern can be inefficient. It would be more performant to create a map so that lookups are O(1) rather than O(n).

const toRemoveMap = toRemove.reduce(
  function(memo, item) {
    memo[item] = memo[item] || true;
    return memo;
  },
  {} // initialize an empty object
);

const filteredArray = myArray.filter(function (x) {
  return toRemoveMap[x];
});

// or, if you want to use ES6-style arrow syntax:
const toRemoveMap = toRemove.reduce((memo, item) => ({
  ...memo,
  [item]: true
}), {});

const filteredArray = myArray.filter(x => toRemoveMap[x]);

Andriy

14.2k4 gold badges45 silver badges49 bronze badges

answered Nov 13, 2013 at 15:17

Ashwin BalamohanAshwin Balamohan

3,2522 gold badges24 silver badges47 bronze badges

1

If you are using an array of objects. Then the below code should do the magic, where an object property will be the criteria to remove duplicate items.

In the below example, duplicates have been removed comparing name of each item.

Try this example. http://jsfiddle.net/deepak7641/zLj133rh/

var myArray = [
  {name: 'deepak', place: 'bangalore'}, 
  {name: 'chirag', place: 'bangalore'}, 
  {name: 'alok', place: 'berhampur'}, 
  {name: 'chandan', place: 'mumbai'}
];
var toRemove = [
  {name: 'deepak', place: 'bangalore'},
  {name: 'alok', place: 'berhampur'}
];

for( var i=myArray.length - 1; i>=0; i--){
 	for( var j=0; j

answered Jul 7, 2015 at 12:18

How about the simplest possible:

var myArray = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
var toRemove = ['b', 'c', 'g'];

var myArray = myArray.filter((item) => !toRemove.includes(item));
console.log(myArray)

MH2K9

11.8k7 gold badges32 silver badges48 bronze badges

answered Aug 7, 2019 at 15:14

Remove array in array javascript

EggonEggon

1,7442 gold badges13 silver badges31 bronze badges

1

I just implemented as:

Array.prototype.exclude = function(list){
        return this.filter(function(el){return list.indexOf(el)<0;})
}

Use as:

myArray.exclude(toRemove);

Remove array in array javascript

pistou

2,7425 gold badges33 silver badges59 bronze badges

answered May 4, 2016 at 9:57

RuneRune

1491 silver badge7 bronze badges

1

If you cannot use new ES5 stuff such filter I think you're stuck with two loops:

for( var i =myArray.length - 1; i>=0; i--){
  for( var j=0; j

answered Nov 13, 2013 at 15:18

Remove array in array javascript

MarcoLMarcoL

9,6693 gold badges36 silver badges50 bronze badges

2

You can use _.differenceBy from lodash

const myArray = [
  {name: 'deepak', place: 'bangalore'}, 
  {name: 'chirag', place: 'bangalore'}, 
  {name: 'alok', place: 'berhampur'}, 
  {name: 'chandan', place: 'mumbai'}
];
const toRemove = [
  {name: 'deepak', place: 'bangalore'},
  {name: 'alok', place: 'berhampur'}
];
const sorted = _.differenceBy(myArray, toRemove, 'name');

Example code here: CodePen

answered Mar 8, 2018 at 11:41

Remove array in array javascript

1

Now in one-liner flavor:

console.log(['a', 'b', 'c', 'd', 'e', 'f', 'g'].filter(x => !~['b', 'c', 'g'].indexOf(x)))

Might not work on old browsers.

answered Jul 18, 2016 at 14:22

This is pretty late but adding this to explain what @mojtaba roohi has answered. The first block of code will not work as each array is having a different object, i.e. df[0] != nfl[2]. Both objects look similar but are altogether different, which is not the case when we use primitive types like numbers.

let df = [ {'name': 'C' },{'name': 'D' }] 
let nfl = [ {'name': 'A' },{'name': 'B' },{'name': 'C' },{'name': 'D' }] 
let res = nfl.filter(x => df.indexOf(x)<0)
console.log(res)

Here is the working code:

let df = [{'name': 'C' },{'name': 'D' }]
let nfl = [ {'name': 'A' },{'name': 'B' },{'name': 'C' },{'name': 'D' }];
let res = nfl.filter((o1) => !df.some((o2) => o1.name === o2.name));
console.log(res)

answered Jun 27, 2021 at 13:13

Remove array in array javascript

Gopal MishraGopal Mishra

1,14311 silver badges17 bronze badges

0

If you're using Typescript and want to match on a single property value, this should work based on Craciun Ciprian's answer above.

You could also make this more generic by allowing non-object matching and / or multi-property value matching.

/**
 *
 * @param arr1 The initial array
 * @param arr2 The array to remove
 * @param propertyName the key of the object to match on
 */
function differenceByPropVal(arr1: T[], arr2: T[], propertyName: string): T[] {
  return arr1.filter(
    (a: T): boolean =>
      !arr2.find((b: T): boolean => b[propertyName] === a[propertyName])
  );
}

answered Sep 4, 2020 at 16:47

onx2onx2

565 bronze badges

Proper way to remove all elements contained in another array is to make source array same object by remove only elements:

Array.prototype.removeContained = function(array) {
  var i, results;
  i = this.length;
  results = [];
  while (i--) {
    if (array.indexOf(this[i]) !== -1) {
      results.push(this.splice(i, 1));
    }
  }
  return results;
};

Or CoffeeScript equivalent:

Array.prototype.removeContained = (array) ->
  i = @length
  @splice i, 1 while i-- when array.indexOf(@[i]) isnt -1

Testing inside chrome dev tools:

19:33:04.447 a=1
19:33:06.354 b=2
19:33:07.615 c=3
19:33:09.981 arr = [a,b,c]
19:33:16.460 arr1 = arr

19:33:20.317 arr1 === arr
19:33:20.331 true

19:33:43.592 arr.removeContained([a,c])
19:33:52.433 arr === arr1
19:33:52.438 true

Using Angular framework is the best way to keep pointer to source object when you update collections without large amount of watchers and reloads.

answered Jul 2, 2018 at 12:45

Remove array in array javascript

1

I build the logic without using any built-in methods, please let me know any optimization or modifications. I tested in JS editor it is working fine.

var myArray = [
            {name: 'deepak', place: 'bangalore'},
            {name: 'alok', place: 'berhampur'},
            {name: 'chirag', place: 'bangalore'},
            {name: 'chandan', place: 'mumbai'},

        ];
        var toRemove = [

            {name: 'chirag', place: 'bangalore'},
            {name: 'deepak', place: 'bangalore'},
            /*{name: 'chandan', place: 'mumbai'},*/
            /*{name: 'alok', place: 'berhampur'},*/


        ];
        var tempArr = [];
        for( var i=0 ; i < myArray.length; i++){
            for( var j=0; j

answered Jul 28, 2018 at 22:12

Remove array in array javascript

//Using the new ES6 Syntax

    console.log(["a", "b", "c", "d", "e", "f", "g"].filter(el => !["b", "c", "g"].includes(el)));

    // OR

    // Main array
    let myArray = ["a", "b", "c", "d", "e", "f", "g"];

    // Array to remove
    const toRemove = ["b", "c", "g"];

    const diff = () => (myArray = myArray.filter((el) => !toRemove.includes(el)));
  console.log(diff()); // [ 'a', 'd', 'e', 'f' ]

    // OR

    const diff2 = () => {
      return myArray = myArray.filter((el) => !toRemove.includes(el));
    };
    console.log(diff2()); // [ 'a', 'd', 'e', 'f' ]

answered Feb 18 at 19:48

brytebeebrytebee

331 silver badge7 bronze badges

A High performance and immutable solution

Javascript

const excludeFromArr = (arr, exclude) => {
  const excludeMap = exclude.reduce((all, item) => ({ ...all, [item]: true }), {});
  return arr.filter((item) => !excludeMap?.[item]);
};

Typescript:

const excludeFromArr = (arr: string[], exclude: string[]): string[] => {
  const excludeMap = exclude.reduce>((all, item) => ({ ...all, [item]: true }), {});
  return arr.filter((item) => !excludeMap?.[item]);
};

answered Feb 24 at 15:52

Remove array in array javascript

Masih JahangiriMasih Jahangiri

7,3572 gold badges40 silver badges39 bronze badges

const first = [
  { key: "Value #1", key1: "Value #11" },
  { key: "Value #2", key1: "Value #12" },
  { key: "Value #3", key1: "Value #13" },
];

const second = [{ key: "Value #1", key1: "Value #11" }];

const toRemove = second.map((x) => Object.values(x).join("."));

const remainingData = first.filter( (x) => !toRemove.includes(Object.values(x).join(".")) );

console.log(JSON.stringify(remainingData, null, 2));

answered Feb 26 at 8:46

How do you remove an array from an array?

There are different methods and techniques you can use to remove elements from JavaScript arrays:.
pop - Removes from the End of an Array..
shift - Removes from the beginning of an Array..
splice - removes from a specific Array index..
filter - allows you to programatically remove elements from an Array..

How do you strip an array in JavaScript?

pop() function: This method is use to remove elements from the end of an array. shift() function: This method is use to remove elements from the start of an array. splice() function: This method is use to remove elements from the specific index of an array.

Can you use Delete in an array in JavaScript?

JavaScript Array delete() Array elements can be deleted using the JavaScript operator delete . Using delete leaves undefined holes in the array. Use pop() or shift() instead.

How do you remove from one array the items that exist in another?

To remove elements contained in another array, we can use a combination of the array filter() method and the Set() constructor function in JavaScript.