2

Let say that we have the JavaScript array arr, where each arr[i] contains a sentence. Now If we want to search for the sentences that contain a particular string str, we can use match to find these sentence using

var newarr = []; for(var i = 0; i < arr.length; i++) { if(arr[i].toLowerCase().match(str.toLowerCase()){ newarr[newarr.length] = arr[i]; } } 

The new array newarr will contain only the sentence that contain the string str. Now, is there a way to rearrange newarr so that the sentences containing str in beginning be first, then the ones that containing str in the middle then the ones containing strin the end?

2 Answers 2

2

The sort method available on Arrays can take a custom function that compares elements and sorts according to that. Your custom sort function needs to take two arguments, a and b, and return a number; a and b are elements of your array which are being compared. The number that your function returns tells the sort function whether a or b should come first, according to the following rules:

  • if the returned number is <0, then a comes before b
  • if the returned number is >0, then b comes before a
  • if the returned number is 0, then a and b are "the same" order-wise

So to order an array of strings according to where a substring str appears, then you can do something like this:

var arr = ['bbbab', 'bbabbb', 'abbb', 'bbbba']; // Our substring. var str = 'a'; // Make copy of array. var newarr = arr.slice() // Sort. newarr.sort(function (a, b) { return a.indexOf(str) - b.indexOf(str); }); console.log(newarr); // => ["abbb", "bbabbb", "bbbab", "bbbba"] 
Sign up to request clarification or add additional context in comments.

9 Comments

a and b are elements of your array that are being compared.
Is there a way to trim each array element using trim() while sorting?
What about abbb, abbbb, abbbbb, etc. How these should be arranged
@user3741635, what do you mean by "trim"? If you want you can just do something newarr = arr.map(function(elt) { return elt.trim(); });.
They all starts with a, but their length is different. indexOf will return 0 for all. According to me, length should also be considered while sorting elements
|
-1

You have forgotten one parenthesis in your if condition.

http://jsfiddle.net/pandeyaditya/LbwgfLvt/

Check below code :

var arr = ["JS is fun", "JS Rocks", "JS is for techies"]; var newarr = []; var str = "fun"; for(var i = 0; i < arr.length; i++) { if(arr[i].toLowerCase().match(str.toLowerCase())){ newarr[newarr.length] = arr[i]; } } alert(newarr); 

1 Comment

In the future, you can just edit the question to fix small issues like this.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.