2

How can I remove all objects from an array based on a property value ?

function removeByKey(array, fieldName){
        array.some(function(item, index) {
            return (array[index].name === fieldName) ? !!(array.splice(index, 1)) : false;
        });
        return array;
    }
    
    const myarr = [
      {
        name: 'foo',
        school: 'hoo'
      },{
        name: 'foo',
        school: 'xooo'
      },{
        name: 'bar',
        school: 'xooo'
      }
    ];
    
    console.log(removeByKey(myarr, 'foo'))

in the above code, it just removes one of the objects. how can i remove all if matches?

teebeetee
  • 549
  • 1
  • 8
  • 23

2 Answers2

5

Why not use filter MDN ?

const myarr = [
  {
    name: 'foo',
    school: 'hoo'
  },{
    name: 'foo',
    school: 'xooo'
  },{
    name: 'bar',
    school: 'xooo'
  }
];

const filteredArray = myarr.filter(obj => obj.name !== 'foo');

Example: https://repl.it/repls/SimultaneousSentimentalForms

Edited to match the comment.

Baruch
  • 2,381
  • 1
  • 17
  • 29
1

You can use the filter function for this:

function removeByKey(arr, propertyValue) {

  return arr.filter(item => item.name !== propertyValue);

}

const myarr = [
  {
    name: 'foo',
    school: 'hoo'
  },{
    name: 'foo',
    school: 'xooo'
  },{
    name: 'bar',
    school: 'xooo'
  }
];

console.log(removeByKey(myarr, 'foo'));

a bit more generic removeByKey function will be:

function removeByKey(arr, propertyName, propertyValue) {

  return arr.filter(item => item[propertyName] !== propertyValue);

}
const myarr = [
  {
    name: 'foo',
    school: 'hoo'
  },{
    name: 'foo',
    school: 'xooo'
  },{
    name: 'bar',
    school: 'xooo'
  }
];

console.log(removeByKey(myarr, 'name', 'foo'));
samee
  • 537
  • 2
  • 9