How can you compare arrays of objects with arrays using JavaScript?
I am looking to evaluate an array of objects based on specific conditions.
If the
targetvalue
is the same and thecode
value is not present in thearraylist
, return the array of objects.Otherwise, if the
targetvalue
is the same and thecode
has the same value in thearraylist
, return the array of objects.
Otherwise, return an empty array []
var arraylist =["IT","FI"];
var arrobj1 =[
{id:1, name: "sonu", code: "IT", targetvalue: "908"},
{id:2, name: "abi", code: "IT", targetvalue: "834"},
{id:3, name: "lisa", code: "SP", targetvalue: "834"},
{id:4, name: "ben", code: "FI", targetvalue: "234"},
]
Expected Output
//same value, and includes `IT`
[]
****
var arrobj2 =[
{id:1, name: "sonu", code: "IT", targetvalue: "908"},
{id:2, name: "abi", code: "IT", targetvalue: "834"},
{id:3, name: "lisa", code: "SG", targetvalue: "234"},
{id:4, name: "ben", code: "SP", targetvalue: "234"},
]
Expected Output
//same targetvalue and not included `FI or IT`, so return
[
{id:3, name: "lisa", code: "SG", targetvalue: "234"},
{id:4, name: "ben", code: "SP", targetvalue: "234"},
]
****
var arrobj3 =[
{id:1, name: "sonu", code: "IT", targetvalue: "908"},
{id:3, name: "lisa", code: "FI", targetvalue: "234"},
{id:4, name: "ben", code: "FI", targetvalue: "234"},
]
Expected Output
// targetvalue and code are the same
[ {id:3, name: "lisa", code: "FI", targetvalue: "234"},
{id:4, name: "ben", code: "FI", targetvalue: "234"}]
I have attempted to use the following code for this comparison:
const checkIdList = list => {
const idlist = ['IN', 'FI'];
const resultarray = list
.map((obj, i) => list.find((elem, index) => {
if (i !== index && elem.targetvalue === obj.targetvalue &&
(element.code === obj.code || idlist.includes(element.code))) {
return obj;
}
}))
.filter(x => x);
return resultarray;
};
var finalResult = this.checkIdList(arrobj1);