Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

javascript - A way to complete for loop before next operation

I have a big array of objects that i got from my rest api and i want to search for a value from one of the elements. I managed to come up with a method that searches the words but it works for a few words and not all. when i tried to find out the problem i realised that the for loop doesnot go through the whole array. below is my code

function search(nameKey, myArray) {
    var lowercased_array = [];
    //lowercase the search value
    var lowercased_nameKey = nameKey.toLowerCase()
    //lowercase the searched array
    for (var i = 0; i < myArray.length; i++) {
        myArray[i].name = myArray[i].name.toLowerCase()
        lowercased_array.push(myArray[i])
    }

    var new_array = [];
    for (var i = 0; i < lowercased_array.length; i++) {
        if ((lowercased_array[i].name).includes(lowercased_nameKey)) {
            new_array.push(lowercased_array[i])
        }
    }
    return new_array
}

i first turn the search word to lowercase , my first for loop is to turn the values for the name element in the array objects to lower case so that the search can take place. The second for loop is to check if the search value exists in the name element of the objects in the array and if true push the whole object in a new array. i am asking for help on how to ensure that the process is complete before returning the new array with the search results.

Thanks in advance


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's unclear why you are creating a lowercased_array, because you already set lowercased values in the provided Array. That being said, your function could probably use filter:

function search(nameKey, myArray) {
  const lowercased_nameKey = nameKey.toLowerCase();
  return myArray.filter(item => item.name.toLowerCase().includes(lowercased_nameKey));
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...