Reputation: 573
I've got 2 sets of javascript objects, one containing a new item and another containing an array of items.
I'd like to be able to check the existing array of items to find out whether the new item falls into any of the existing items, based on two pairs of keys and values (these being dateFrom
and dateTo
, and ideally even if the new item falls in-between any of the dates in the existing items).
const newItem = [{
id: null,
dateFrom: '2019-02-01',
dateTo: '2019-02-28'
}]
const existingItems = [{
id: 1,
dateFrom: '2019-01-01',
dateTo: '2019-01-31'
},{
id: 2,
dateFrom: '2019-02-01',
dateTo: '2019-02-28'
},{
id: 3,
dateFrom: '2019-03-01',
dateTo: '2019-03-31'
}]
What I'd like is to be able to pass both items to a function that will return a boolean answer that states whether the new item doesn't exist in the existing collection of items. Thanks in advance! I'm guessing something along the lines of:
checkDateRanges(newItem, existingItems) {
forEach.existingItems(item => {
item.dateFrom = newItem.dateFrom ||
item.dateTo = newItem.dateTo
})
}
Upvotes: 0
Views: 567
Reputation: 988
The best way I can think of solving this is by using Javascripts Array.some
method, which returns a boolean if the callback returns true for any of the value within the array. As a bonus, it stops as soon as it sees a true
value.
So you are comparing 2 arrays, my solution would look like this, which could be interpreted to the newItem
is contained within the existingItems
array based on the logic you provided.
function checkDateRanges(newItem, existingItems) {
return existingItems.some((item) => {
return item.dateFrom === newItem.dateFrom ||
item.dateTo === newItem.dateTo;
});
}
Upvotes: 0
Reputation: 7464
You're very close with what you've got there. First, the array function find might be a good choice. It will only find the first match, which is often more efficient than looping through the whole array. It would look something like this:
function checkDateRanges(newItem, existingItems) {
const match = existingItems.find(item=>
item.dateFrom == newItem.dateFrom &&
item.dateTo == newItem.dateTo
);
return match!==undefined;
}
As you say this will return a boolean. But of course you could also return the actual object match, or if you wanted the array index of the match, there is also findIndex.
The other thing to note is that your newItem
above is an array containing a single object. I'm guessing you might want to remove the array brackets from around that object. But with newItem
and existingItems
exactly as you have them above, you would need to invoke the function like this (to get the first element of that array):
checkDateRanges(newItem[0], existingItems);
Upvotes: 1