user1885099
user1885099

Reputation: 150

Javascript/jQuery: Remove item from multidimensional array by value

I have a dynamically generated multidimensional array from which I want to remove a specific value.

I have this code, so far:

mainARR = [[1,2,3,4], [5,6,7,8]];
delARR = [1,2,3,4];

function removeByValue(array, value){
    return array.filter(function(elem, _index){
        return value != elem;
    });
}
mainARR = removeByValue(mainARR, delARR);

console.log(JSON.stringify(mainARR));

I don't know the index of the value I want to remove. Instead, I know the actual value. The code does not work when the value is an array. It works perfectly for simple arrays like [1,2,3,4] when I want to remove, let's say, the value 1.

Any help is appreciated.

Upvotes: 0

Views: 1465

Answers (3)

If you make the elem and value into a string then your code works just fine.

function removeByValue(array, value) {
  return array.filter(function(elem, _index) {
    return value.toString() != elem.toString();
  });
}

Example below

mainARR = [
  [1, 2, 3, 4],
  [5, 6, 7, 8]
];
delARR = [1, 2, 3, 4];

function removeByValue(array, value) {
  return array.filter(function(elem, _index) {
    return value.toString() != elem.toString();
  });
}
mainARR = removeByValue(mainARR, delARR);

console.log(JSON.stringify(mainARR));

Upvotes: 3

Nina Scholz
Nina Scholz

Reputation: 386560

You could filter the values and then delete empty arrays as well.

var mainARR = [[1, 2, 3, 4], [5, 6, 7, 8]],
    delARR = [1, 2, 3, 4],
    result = mainARR.map(a => a.filter(b => !delARR.includes(b))).filter(a => a.length);

console.log(result);

Upvotes: 1

lnx
lnx

Reputation: 56

You will have to compare every element inside array. Example solution:

mainARR = [[1,2,3,4], [5,6,7,8]];
delARR = [1,2,3,4];

function removeByValue(array, value){
    return array.filter(function(elem, _index){
        // Compares length and every element inside array
        return !(elem.length==value.length && elem.every(function(v,i) { return v === value[i]}))
    });
}
mainARR = removeByValue(mainARR, delARR);

console.log(JSON.stringify(mainARR));

This should work on sorted and unsorted arrays.

Upvotes: 1

Related Questions