javascript array includes object id code example

Example 1: how to delete an element of an array in javascript

//you can use two functions depending of what you want to do:

let animals1 = ["dog", "cat", "mouse"]
delete animals1[1]
/*this deletes all the information inside "cat" but the element still exists
so now you'll have this:*/
console.log(animals1)//animals1 = ["dog", undefined, "mouse"]

//if you want to delete it completely, you have to use array.splice:

let animals2 = ["dog", "cat", "mouse"]
animals2.splice(1, 1)
/*the first number means the position from which you want to start to delete
and the second is how much elements will be deleted*/
console.log(animals2)//animals2 = ["dog", "mouse"]
/*Now you don't have undefined
If you did this:*/
let animals3 = ["dog", "cat", "mouse"]
animals3.splice(0, 2)//you'll have this:
console.log(animals3)//animals 3 = "mouse"
/*This happens because I put a 2 in the second parameter so it deleted
two elements from position 0
Try copying this code in your console and whatch*/

Example 2: angular list contains property

vendors.filter(function(vendor){ return vendor.Name === "Magenic" })

Example 3: javascript array contains object

// Works in all browsers
if (array.index(object) !== -1) {
  console.log(`my object is in my array`)
}

// ES7 :
if(array.includes(oject)) {
  console.log(`my object is in my array`)
}

Example 4: check unique object in array javascript site:stackoverflow.com

var data = [
{name:"Joe", date:'2018-07-01', amt:250 },
{name:"Mars", date:'2018-07-01', amt:250 },
{name:"Joe", date:'2018-07-02', amt:250 },
{name:"Saturn", date:'2018-07-01', amt:250 },
{name:"Joe", date:'2018-07-02', amt:250 },
{name:"Jupiter", date:'2018-07-01', amt:250 },
]
var resArr = [];
data.filter(function(item){
  var i = resArr.findIndex(x => (x.name == item.name && x.date == item.date && x.amt == item.amt));
  if(i <= -1){
        resArr.push(item);
  }
  return null;
});
console.log(resArr)

Tags:

Php Example