Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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.includes(needle)) {
- 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"
- }
- }
- ]
- */
Add Comment
Please, Sign In to add comment