简体   繁体   中英

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.

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)); 

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.

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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM