简体   繁体   English

如何对数组进行排序,以便在 position 中获得特定值?

[英]How to sort an array so that I get a specific value at position one?

If I have an array of:如果我有一个数组:

var myArray = ["one", "two", "yay", "something", "something else", "some more"];

And want to rearange the array so that the value "yay" is at position 0并希望重新排列数组,使值“yay”位于 position 0

var positionOneValue = "yay";
var sortedArray = myArray ... 

My attempt:我的尝试:

var sorted = myArray.sort((item) => {
    if(positionOneValue.match(item))
       return item;
     
    return null; // this is probably wrong
})

how do i accomplish this?我该如何做到这一点?

You could check for the value and move the value to top with the delta of the checks.您可以检查该值并使用检查的增量将该值移动到顶部。

 var array = ["one", "two", "yay", "something", "something else", "some more"]; array.sort((a, b) => (b === 'yay') - (a === 'yay')); console.log(array);

If the idea is to keep everything else in the same order, you can use indexOf , splice and unshift :如果您的想法是让其他所有内容保持相同的顺序,您可以使用indexOfspliceunshift

 var myArray = ["one", "two", "yay", "something", "c", "b", "a", "something else", "some more"]; var yayIndex = myArray.indexOf("yay"); if (yayIndex > -1) { myArray.unshift(myArray.splice(yayIndex, 1)[0]); } console.log(myArray);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM