0

I am looking for better way to handle the search of array. This is what I have right now.

function search (arr, word) {
  word = word.toUpperCase();
  var res = [];
  for(var i = 0; i < arr.length; i++) {
    if(arr[i].slice(0, word.length) == word) {
      res.push(arr[i]);
    }
  }
  return res;
}

var myArr = ["england", "China", "France", "Eng", "Ch", "Australia"];

search(myArr, "e");

It works, but I would like to replace for loop with ES6 code as I am trying to learn it. How could I utilize ES6 here?

6
  • es6 is a spec, not a function/method call. What do you mean by replace it with es6? Commented Jun 27, 2017 at 13:49
  • Unrelated but it looks like there's a bug as you convert the word to uppercase, but not the words in the array. So for example, it won't return "england" for the letter "e". Commented Jun 27, 2017 at 13:52
  • @Polina Your current code is only returning Eng not england Commented Jun 27, 2017 at 13:52
  • 1
    What is 'better'? While not being good-looking solution, for is likely the most performant solution. Commented Jun 27, 2017 at 13:56
  • @Weedoze Hmm... It works for me thought here is my repo - repl.it/JDvw Commented Jun 27, 2017 at 14:08

1 Answer 1

3

You could utilize a few builtin methods such as String#startsWith and Array#filter:

function search(arr, word) {
  return arr.filter(element => element.toUpperCase().startsWith(word.toUpperCase()));
}

const myArr = ["england", "China", "France", "Eng", "Ch", "Australia"];
console.log(search(myArr, "e"));

The filter method only keeps elements in the array that meet the certain condition specified by the callback. Thus it checks if the element starts with the word regardless of case.

And if you need support for IE, try using String#indexOf:

element.toUpperCase().indexOf(word.toUpperCase()) == 0

This will check if the element starts with the specified string, regardless of case and is functionally equivalent.


Note that although it doesn't look pretty, the for loop is a better in terms of performance as estus noted. After testing it looks like it takes the for loop around 0.1 milliseconds to complete and my solution ranges from 0.2 to 0.7 milliseconds to complete. Though there's a difference, I wouldn't worry about performance until it really matters -- but the faster one here is your solution.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, this is just something I wanted! Much shorter and nicer than my code, thanks a lot!
thank you for explanation and comment about for loop!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.