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?

1
  • Change !! to ! Commented Aug 7, 2018 at 10:25

2 Answers 2

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.

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

2 Comments

i mean, i need to REMOVE not keep the matches.
... Then do obj.name !== 'foo' .... @storis I edited my answer to match what you need.
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'));

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.