Skip to content

Instantly share code, notes, and snippets.

@maxmarinich
Last active June 14, 2018 15:07
Show Gist options
  • Save maxmarinich/8a6a76fc1bc78647c96952df3c5bd505 to your computer and use it in GitHub Desktop.
Save maxmarinich/8a6a76fc1bc78647c96952df3c5bd505 to your computer and use it in GitHub Desktop.
Find values in array by tags
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