-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?

0

2 Answers 2

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);

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

2 Comments

Thank you @acbay
Isn't it an answer? If it is, can you mark?
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.

1 Comment

I am not clear enough, would you please elaborate you description or can you give an example.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.