[英]Array.sort() only for elements that have a specific key
我有一個像這樣的數組:
let arr = [
{
label: "abc",
value: 2,
checked: true
},
{
label: "bcd",
value: 1,
checked: true
},
{
label: "cde",
value: 4,
checked: false
},{
label: "def",
value: 6,
checked: true
},
{
label: "efg",
value: 3,
checked: false
},
{
label: "fgh",
value: 5,
checked: true
}
]
我試圖以兩種不同的方式對它進行排序(按字母順序,按值)。 該排序的當前實現正常工作,但是當我按值進行排序時,我遇到了一些問題...如何僅在檢查標志為“真的? 我的意思是...我只想按值排序被檢查的元素和元素的 rest 以將它們保留在初始索引處...
//expected result
let arr = [
{ //sorted index 0
label: "bcd",
value: 1,
checked: true
},
{ //sorted index 1
label: "abc",
value: 2,
checked: true
},
{ //checked: false - perserve index (2) from the initial array
label: "cde",
value: 4,
checked: false
},
{ //sorted index 3
label: "fgh",
value: 5,
checked: true
},
{ //checked: false - perserve index (4) from the initial array
label: "efg",
value: 3,
checked: false
},
{ //sorted index 5
label: "def",
value: 6,
checked: true
}
]
有沒有簡單的方法來使用 lodash? 還是需要手動完成,如何操作?
您可以存儲索引以將已排序的值放回原處並獲取對象進行排序。 排序並申請回來。
var array = [{ label: "abc", value: 2, checked: true }, { label: "bcd", value: 1, checked: true }, { label: "cde", value: 4, checked: false }, { label: "def", value: 6, checked: true }, { label: "efg", value: 3, checked: false }, { label: "fgh", value: 5, checked: true }], indices = []; array.filter(({ checked }, i) => checked && indices.push(i)).sort(({ value: a }, { value: b }) => a - b).forEach((v, i) => array[indices[i]] = v); console.log(array);
.as-console-wrapper { max-height: 100%;important: top; 0; }
該解決方案的工作原理是將選中的項目復制到一個單獨的數組中,對它們進行排序,然后將它們重新插入到原始數組(的副本)中。
const // Gets the original array arr = getArr() // Defines a function to use for sorting compare = (a, b) => a.value - b.value, // Makes an array of just the objects where `.checked` is truthy, and sorts it partSorted = arr.filter(obj => obj.checked).sort(compare); // Defines a variable to track the index within the `partSorted` array let i = 0; // Copies `arr`, but substitutes the next item from `partSorted` if appropriate const sorted = arr.map(obj => obj.checked? partSorted[i++]: obj ); // Shows the result console.log(sorted); // Defines the original array function getArr(){ return [ { label: "abc", value: 2, checked: true }, { label: "bcd", value: 1, checked: true }, { label: "cde", value: 4, checked: false }, { label: "def", value: 6, checked: true }, { label: "efg", value: 3, checked: false }, { label: "fgh", value: 5, checked: true } ]; }
您可以使用原生 JavaScript 排序。 1和-1改變排序position,0將保持順序。 如果相反,則將 a 更改a
b
。
arr.sort((a, b) => a.checked ? b.value - a.value : 0);
我知道我遲到了,但這是使用冒泡的不同方法
for(let i=0;i<arr1.length-1;i++){
for(let j=0;j<arr1.length-i-1;j++){
if(arr1[j].checked==true){
if(arr1[j].value>arr1[j+1].value){
v=arr1[j]
arr1[j]=arr1[j+1]
arr1[j+1]=v
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.