Umbro
Umbro

Reputation: 2204

Comparing 'id' via the findIndex method

If todos of thetodo object is not found in the array. Add todo to thetodos array. If found, do not add to the board. Compares if the table is todo with the given index. Returns -1 to me, or false. I do the condition if (! findObject) {} should add the object to the array instead of adding it

Code here: https://stackblitz.com/edit/react-7wlg5m

const todos = [
  {
    "userId": 1,
    "id": 1,
    "title": "delectus aut autem",
    "completed": false
  },
  {
    "userId": 1,
    "id": 2,
    "title": "quis ut nam facilis et officia qui",
    "completed": false
  },
  {
    "userId": 1,
    "id": 5,
    "title": "fugiat veniam minus",
    "completed": false
  }
]

const todo = {
  "userId": 1,
  "id": 3,
  "title": "delectus aut autem",
  "completed": false
}

  let findObject = todos.findIndex(x => x.id === todo.id);
  console.log(findObject);

if(!findObject) {
  let newArray = [...todos];

  newArray.push(todo)
  console.log(newArray)
}

Upvotes: 1

Views: 401

Answers (3)

Ronak Lalwani
Ronak Lalwani

Reputation: 386

You can also use filter method to filter out matching id. You can do something like this:

let findObject = todos.filter(x => x.id === todo.id);
console.log(findObject);

if (!findObject.includes(todo.id)) {  
  let newArray = [...todos];
  newArray.push(todo);
  console.log(newArray);
}

You can find out more about filter method from here : [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter]

Hope this helps 🙂

Upvotes: 0

Ali Ilman
Ali Ilman

Reputation: 180

An alternative to Jack Bashford's answer is to use .find instead of .findIndex.
.find returns undefined if the todo is not found in the todos array, and undefined is a falsy value.

Array.prototype.find() - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find


let findObject = todos.find(x => x.id === todo.id);
console.log(findObject);

if(!findObject) {
  let newArray = [...todos];

  newArray.push(todo)
  console.log(newArray)
}

Working example: https://repl.it/repls/TemporalLividCodegeneration

Upvotes: 2

Jack Bashford
Jack Bashford

Reputation: 44115

findIndex will return -1 if the item is not found, and unfortunately, that is not a falsy value - the only falsy number value is 0. All others - including -1 - are truthy.

console.log(!!-1);

So you should check against -1 in your condition:

if (findObject == -1) {
  // ...
}

Upvotes: 3

Related Questions