Guest User

Untitled

a guest
Jun 13th, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.34 KB | None | 0 0
  1. const searchIn = (string, haystack) => {
  2. const result = []
  3. const matches = []
  4. const values = string.replace(/[^\wа-яё\s]/gi, '')
  5.  
  6. haystack.forEach((item) => {
  7. let matchesCount = 0
  8.  
  9. values.split(' ').forEach((needle) => {
  10. if (needle && item.tags.includes(needle)) {
  11. matchesCount += 1
  12. }
  13. })
  14.  
  15. if (matchesCount) {
  16. matches.push(matchesCount)
  17. result.push({ matchesCount, item })
  18. }
  19. })
  20.  
  21. const maxMatchedValue = Math.max(...matches)
  22. return result.filter(({ matchesCount }) => matchesCount === maxMatchedValue)
  23. }
  24.  
  25. const arr1 = [
  26. {id: 1, tags: 'some, value, values, empty...'},
  27. {id: 2, tags: 'some, value'},
  28. {id: 3, tags: 'some'},
  29. {id: 4, tags: ''},
  30. ]
  31. const arr2 = [
  32. {id: 1, tags: 'some, values, empty'},
  33. {id: 2, tags: 'empty, value'},
  34. {id: 3, tags: 'value'},
  35. {id: 4},
  36. ]
  37.  
  38. const searchString = 'some values searching not including...'
  39. const filterByTags = (arr) => arr.filter(({ tags }) => tags && tags.length)
  40. const haystack = [arr1, arr2].map(filterByTags).reduce((a, b) => a.concat(b))
  41.  
  42. searchIn(searchString, haystack)
  43.  
  44. /*
  45. [
  46. {
  47. "matchesCount": 2,
  48. "item": {
  49. "id": 1,
  50. "tags": "some, value, values, empty..."
  51. }
  52. },
  53. {
  54. "matchesCount": 2,
  55. "item": {
  56. "id": 1,
  57. "tags": "some, value, values, empty"
  58. }
  59. }
  60. ]
  61. */
Add Comment
Please, Sign In to add comment