Last active
June 14, 2018 15:07
-
-
Save maxmarinich/8a6a76fc1bc78647c96952df3c5bd505 to your computer and use it in GitHub Desktop.
Find values in array by tags
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const searchIn = (string, haystack) => { | |
const result = [] | |
const matches = [] | |
const values = string.replace(/[^\wа-яё\s]/gi, '') | |
haystack.forEach((item) => { | |
let matchesCount = 0 | |
values.split(' ').forEach((needle) => { | |
if (needle && item.tags.toLowerCase().includes(needle.toLowerCase())) { | |
matchesCount += 1 | |
} | |
}) | |
if (matchesCount) { | |
matches.push(matchesCount) | |
result.push({ matchesCount, item }) | |
} | |
}) | |
const maxMatchedValue = Math.max(...matches) | |
return result.filter(({ matchesCount }) => matchesCount === maxMatchedValue) | |
} | |
const arr1 = [ | |
{id: 1, tags: 'some, value, values, empty...'}, | |
{id: 2, tags: 'some, value'}, | |
{id: 3, tags: 'some'}, | |
{id: 4, tags: ''}, | |
] | |
const arr2 = [ | |
{id: 1, tags: 'some, values, empty'}, | |
{id: 2, tags: 'empty, value'}, | |
{id: 3, tags: 'value'}, | |
{id: 4}, | |
] | |
const searchString = 'some values searching not including...' | |
const filterByTags = (arr) => arr.filter(({ tags }) => tags && tags.length) | |
const haystack = [arr1, arr2].map(filterByTags).reduce((a, b) => a.concat(b)) | |
searchIn(searchString, haystack) | |
/* | |
[ | |
{ | |
"matchesCount": 2, | |
"item": { | |
"id": 1, | |
"tags": "some, value, values, empty..." | |
} | |
}, | |
{ | |
"matchesCount": 2, | |
"item": { | |
"id": 1, | |
"tags": "some, value, values, empty" | |
} | |
} | |
] | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment