0

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.

1
  • please add the wanted result. do you keep an empty array? or would you like to delete the whole array with the given values? Commented Aug 22, 2017 at 8:22

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.