array filter includes javascript code example

Example 1: how to check if an element exists in an array of objects js

var arr = [{ id: 1, username: 'fred' }, 
  { id: 2, username: 'bill'}, 
  { id: 3, username: 'ted' }];

function userExists(username) {
  return arr.some(function(el) {
    return el.username === username;
  }); 
}

console.log(userExists('fred')); // true
console.log(userExists('bred')); // false

Example 2: how the filter() function works javascript

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];

const filter = arr.filter((number) => number > 5);
console.log(filter); // [6, 7, 8, 9]

Example 3: filter out object in array using two arguments

var arr= [{id: "123", name: "Faa"},
          {id: "123", name: "Bar"},
          {id: "345", name: "Foo"},
          {id: "678", name: "FaaBar"}
         ];

var name = 'FaaBar';
var id = '678';

arr = arr.filter(function(elem) {
  //return false for the element that matches both the name and the id
  return !(elem.id == id && elem.name == name)
});