im building an api which needs to find the longest path that matches a number in a very performant manner.
eg
// API Request
{
'number': '123456789'
}
// DATA
[
{
'prefix': '1',
'price': 30.5
},
{
'prefix': '123',
'price': 10.5
},
{
'prefix': '12345',
'price': 22.5
},
]
// API RESPONSE
{
'prefix': '12345',
'price': 22.5
},
As you can see from above the response should be the row with prefix of 12345 as it is the longest. please i need a bit of help in doing this. i have spent about 2 days now looking for a solution so i decided to come to stack overflow for answers. Thanks in advance!
yourData.reduce((longest, current) => { your logic here }, null)
prefix
ie,12345
? If you can mutate thedata
then please try:data.sort((a, b) => { return a.prefix.length > b.prefix.length ? 1 : -1 })[0];
. It's bit more tricky if you are not allowed to mutatedata
. Please see what this gets you:const longest = data.find(x => x.prefix.length === Math.max(...data.map(y => y.prefix.length))) ;
. Let us know how it goes.const max = Math.max(...DATA.map(obj => obj.prefix.length));
thenconst result = DATA.find(obj => obj.prefix.length === max);