2

I have created a list

let keywords = ['do', 'if', 'in', 'for', 'new', 'try', 'for','var'];

now I'm able to filter based on the string and I'm able to sort in descending and ascending order also.

But I'm unable to sort based on the string,

EX:- I need to sort the list with 'for' (for needs to come on the top of the list and remaining will be as it is).

3
  • What exactly is your criteria for sort? Maybe you're looking to sort on filtered results. But that's something that's not really clear from your question. Commented Nov 20, 2018 at 12:31
  • so you are expecting something like ['for,'for','do', 'if', 'in', 'new', 'try','var']; ?? Commented Nov 20, 2018 at 12:40
  • yes exactly same Commented Nov 20, 2018 at 12:57

3 Answers 3

2

Basically you just need to change the callback of the sort function:

let keywords = ['do', 'if', 'in', 'for', 'new', 'try', 'for','var'];

const sortWithWord = (words, firstWord) => words.sort((a, b) => {
    if (a === firstWord) return -1;
    return a.localeCompare(b);
});

//will print  ["new", "do", "for", "for", "if", "in", "try", "var"]
console.log(sortWithWord(keywords, "new"));

The condition for sorting can be different of course, but if you want a certain word to be first, you'll have to return a negative value when it is compared.

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

Comments

1

As far as I understand, you want to slice sorted list, like this:

keywords.sort();
var result = keywords.slice(keywords.findIndex(function(item){ return item == "for"; }));

Comments

0
let keywords = ['do', 'if', 'in', 'for', 'new', 'try', 'for','var'];
let spliceArray = keywords; //For this line there is for sure a more elegant solution.

const queryIndex = keywords.findIndex(entry => entry === 'for');

spliceArray.splice(queryIndex, 1);

const newKeywords = [keywords[queryIndex], ...spliceArray];

Comments

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.