0

I have a nested array I loop through it and check if a value includes a search string then push the values that includes the search string into a new array. Then I sort the new array by occurrence of the search string so that the index position of every element in the new array depends how similar the array element string is with the search string and also the array elements will be sorted by ascending letter order. Now my code below works fine if all the array elements have the same capitalization but if the capitalization of the array elements are mixed (between lower and upper case) the the sort algorithm fails. Where did I go wrong and how can I fix it? Take a look at my code to better understand the question. Thanks in advance.

const allArr = [
  [{
    "id": "1",
    "title": "blaha"
  }, {
    "id": "2",
    "title": "blahe"
  }, {
    "id": "3",
    "title": "dhs"
  }],
  [{
    "id": "4",
    "title": "BLAHc"
  }, {
    "id": "5",
    "title": "shg"
  }]
]

const searchTerm = 'blah'
let existsArr = []
let tempArr = []

for (var i = 0; i < allArr.length; i++) {
  const allAds = allArr[i]
  for (var j = 0; j < allAds.length; j++) {
    if (allAds[j].title.toLowerCase().includes(searchTerm.toLowerCase())) {
      existsArr.push(allAds[j].title)
    }
  }
}

tempArr = existsArr.filter(a => a.toLowerCase().includes(searchTerm))
const startsWith = (string, value) => string.substring(0, value.length).toLowerCase() === value

const sortByOccurance = tempArr.sort((a, b) => {
  const aStartsWith = startsWith(a, searchTerm)
  const bStartsWith = startsWith(b, searchTerm)

  if (aStartsWith && !bStartsWith) {
    return -1
  } else if (!aStartsWith && bStartsWith) {
    return 1;
  }

  return b > a ? -1 : 1
})

//should have logged ["blaha", "BLAHc", "blahe"], works correctly if all the array elements had the same capitalization
console.log(sortByOccurance)
seriously
  • 1,202
  • 5
  • 23

0 Answers0