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 e on the top of the list and remaining will be as it is).
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 e on the top of the list and remaining will be as it is).
Share Improve this question asked Nov 20, 2018 at 12:29 Sivamohan ReddySivamohan Reddy 5742 gold badges9 silver badges28 bronze badges 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. – SiddAjmera Commented Nov 20, 2018 at 12:31
- so you are expecting something like ['for,'for','do', 'if', 'in', 'new', 'try','var']; ?? – Deepender Sharma Commented Nov 20, 2018 at 12:40
- yes exactly same – Sivamohan Reddy Commented Nov 20, 2018 at 12:57
3 Answers
Reset to default 2Basically 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 pared.
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"; }));
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];
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744278469a4566451.html
评论列表(0条)