-4

I'm trying to remove one or few objects from array. Which meet the condition completed === true. Array can dynamically contain more or less objects.

const array = [{
    completed: false,
    id: 1595572089666,
    title: "1"
  },
  {
    completed: false,
    id: 1595572089666,
    title: "2"
  },
  {
    completed: true,
    id: 1595572089666,
    title: "3"
  },
  {
    completed: true,
    id: 1595572089666,
    title: "4"
  },
  {
    completed: false,
    id: 1595572089666,
    title: "5"
  }
];

function removeCompleted(arr) {
  arr.reduce(item => {
    return item.completed === true ? item.splice(1, 1) : false;
  });
}
Imp3l
  • 101
  • 4
  • 1
    Have you tried `Array.prototype.filter()`? `const filtered = array.filter(({ completed }) => !completed)` – Phil Jul 24 '20 at 06:34
  • 1
    Does this answer your question? [How can I remove a specific item from an array?](https://stackoverflow.com/questions/5767325/how-can-i-remove-a-specific-item-from-an-array) – glinda93 Jul 24 '20 at 06:35
  • 1
    From the duplicate, see [this answer](https://stackoverflow.com/a/20690490/283366) – Phil Jul 24 '20 at 06:37

1 Answers1

2

You can use filter method to remove object based on completed property.

let array = [{
    completed: false,
    id: 1595572089666,
    title: "1"
  },
  {
    completed: false,
    id: 1595572089666,
    title: "2"
  },
  {
    completed: true,
    id: 1595572089666,
    title: "3"
  },
  {
    completed: true,
    id: 1595572089666,
    title: "4"
  },
  {
    completed: false,
    id: 1595572089666,
    title: "5"
  }
];

array = array.filter(item => item.completed != true);

console.log(array);
Ferin Patel
  • 1,560
  • 2
  • 4
  • 32
  • 1
    i want remove items from existing array without creating new array – Imp3l Jul 24 '20 at 06:38
  • This will not create new array. It will just overwrite existing array without using extra memory – Ferin Patel Jul 24 '20 at 06:42
  • _The [filter()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) method creates a **new** array with all elements that pass the test implemented by the provided function._ – Nikita Madeev Jul 24 '20 at 07:09