-1

I am facing a problem with array sorting. I am trying to do a customized sort. I mean let's say if I take an array like the one below and I want to sort it according to my criteria. For example, I want my new sorted array will start the names which begin with letter 'h' and after this, it will go normally.

let names = ['monkey', 'ziraf', 'cat', 'hridoy','htido', 'bhuyan'];

I want my new sorted array like this:

names = ['hridoy', 'htido', 'bhuyan', 'cat', 'monkey', 'ziraf'];

Any ideas?

Gaurav Mall
  • 2,372
  • 1
  • 17
  • 33
Hridoy
  • 23
  • 3

2 Answers2

0

Okay. So you want to sort your array based on if it contains letter 'h'. You have to declare a new empty array first and for loop through the first array. If the element has h as the first letter in the string, add it to the new empty array and delete it from the first array. Then, just for loop again through the new first array and add all elements to new array. Set first array = to new array.

  • I am not clear enough, would you please elaborate you description or can you give an example. – Hridoy May 12 '20 at 08:01
0

let names = ['monkey', 'ziraf', 'cat', 'hridoy','htido', 'bhuyan'];

names.sort(function(x, y) {
  if(x.indexOf("h")===0 && y.indexOf("h")===0){
    x.slice(1);
    y.slice(1);
  } else{
    if (x.indexOf("h")===0) {
      return -1;
    } else if(y.indexOf("h")===0){
      return 1;
    }
  }

  if(x>y){
    return 1;
  } else if(y>x){
    return -1;
  } else{
    return 0;
  }
});

document.write(names);
acbay
  • 832
  • 7
  • 7