I have 2 arrays object below:
- var data: The complete data
- var choose: The only choose
var data = [
{
"day": "Mon",
"id": "SC0001",
"deviceID": "DA0002",
"time": "08:00",
"trigger": "ON"
},
{
"day": "Wed",
"id": "SC0001",
"deviceID": "DA0002",
"time": "08:00",
"trigger": "ON"
},
{
"day": "Fri",
"id": "SC0001",
"deviceID": "DA0002",
"time": "08:00",
"trigger": "ON"
},
{
"day": "Sat",
"id": "SC0001",
"deviceID": "DA0002",
"time": "08:00",
"trigger": "ON"
},
{
"day": "Sun",
"id": "SC0001",
"deviceID": "DA0002",
"time": "08:00",
"trigger": "ON"
}
];
var choose = [
{
"deviceID": "DA0002",
"id": "SC0001",
"day": "Mon",
"time": "08:00",
"trigger": "ON"
},
{
"deviceID": "DA0002",
"id": "SC0001",
"day": "Wed",
"time": "08:00",
"trigger": "ON"
},
{
"deviceID": "DA0002",
"id": "SC0001",
"day": "Sat",
"time": "08:00",
"trigger": "ON"
},
{
"deviceID": "DA0002",
"id": "SC0001",
"day": "Sun",
"time": "08:00",
"trigger": "ON"
}
];
for(var i=0; i<data.length; i++) {
var day = data[i].day;
var scheduleID = data[i].id;
var deviceID = data[i].deviceID;
console.log(day);
//How to get Friday array here?
}
As We can see above if compare with both array object, I need to get the unlisted result.
So how can I get the array object for Friday only?
2
Answers
Use
Array::filter()
to filter your data array and useArray::some()
in the filter callback to check that the current item’s day doesn’t exist in the choose array.It works if
day
is unique per an object in an array, otherwise you should compare several unique fields.I’m assuming that you want to filter away all the entries from
choose
fromdata
. A basic solution would be to useArray.filter()
, which runs a function over all items and only keeps the ones where a truthy value was returned:However, the code above will not work properly here because the data in
data
, while having the same representation in code, will never be equal (i.e. ===) that inchoose
because of how JS handles objects – objects will only be considered "equal" if they are equal by reference:In this case, you will need a deep-equals comparison, which looks at the individual keys and values of objects. A quick hack would be comparing two objects’
JSON.stringify()
representations:However you can also to look into using libraries, such as
deep-equal
:Hope this helps!