Reputation: 862
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 str
in the end?
Upvotes: 2
Views: 90
Reputation: 4030
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:
<0
, then a
comes before b
>0
, then b
comes before a
0
, then a
and b
are "the same" order-wiseSo 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"]
Upvotes: 2
Reputation: 1027
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);
Upvotes: -1