Basically I have an array links and an array linksElem, I want to check if the gridId element of the array(links) is present in the linksElem array. I am expecting a boolean
const links = [
{ gridId: 106590, configuration: {} },
{ gridId: 106596, configuration: {} },
{ gridId: 106578, configuration: {} },
{ gridId: 107014, configuration: {} },
{ gridId: 106578, configuration: {} }
];
const linksElem = [
{ GridId: 106590, IsFamily: true, Total: 0, Tables: Array(0) },
{ GridId: 106596, IsFamily: true, Total: 0, Tables: Array(0) },
{ GridId: 106578, IsFamily: true, Total: 0, Tables: Array(0) },
{ GridId: 107014, IsFamily: true, Total: 0, Tables: Array(0) },
{ GridId: 106578, IsFamily: true, Total: 0, Tables: Array(0) }
];
const res =
links?.some((el) => el.gridId === linksElem.GridId);
CodePudding user response:
Here is the solution.. this will return true if any of gridId in links exists in gridId of linksElem
var linkids = linksElem.map(d=>d.GridId)
var res = links.some(d=> linkids.includes(d.gridId))
console.log(res)
CodePudding user response:
you have to use the following code but unfortunately it is of O(n^2) but i will write a solution of O(n) afterwards
const existsInLinksElem = (gridId)=>{
for (const item of LinksElem) {
if(item.gridId===gridId) return true
}
return false
}
and you can call this function for each element in the links array
if you would like to do it fatser you'd better change the way you are storing your data from an array to an object with the keys being the gridIds in this way :
const links = [
{ gridId: 106590, configuration: {} },
{ gridId: 106596, configuration: {} },
{ gridId: 106578, configuration: {} },
{ gridId: 107014, configuration: {} },
{ gridId: 106578, configuration: {} }
];
const linksElem = {
106590:{ GridId: 106590, IsFamily: true, Total: 0, Tables: Array(0) },
106596:{ GridId: 106596, IsFamily: true, Total: 0, Tables: Array(0) },
106578:{ GridId: 106578, IsFamily: true, Total: 0, Tables: Array(0) },
107014:{ GridId: 107014, IsFamily: true, Total: 0, Tables: Array(0) },
106578:{ GridId: 106578, IsFamily: true, Total: 0, Tables: Array(0) }
};
and the function would be like:
const existsInLinksElem = (gridId)=>{
return !!(linksElem[gridId])
}
note that you will loose nothing because anywhere that you've used the array of linkElems, you can use Object.values(linkElems) instead and have the exact same array returned