![](/img/trans.png)
[英]Bubble sort ins't looping through entire array. Can someone help point out what's incorrect
[英]Can't Sort data from an array. sort is not a function
我正在嘗試對數組中的數據進行排序,從次要到最大。 我得到錯誤: time.sort
is not a function, time.sort
is undefined
。
這是我的代碼:
{
this.state.measure.map((data, index) => {
let time = data.duration
const totalTime = time.sort((a, b) => parseFloat(a.time) - parseFloat(b.time))
console.log(totalTime)
})
}
如果我 console.log(time) 我收到 15:00, 12:00, 50:00, 15:10 這是我想要排序的數據,但首先我需要使用 parseFloat() 轉換為數字,然后使用下單,反正這不是問題。 看起來sort()
是我的代碼中的問題。 這是我的 JSON。
{
"measures": [
{
"_id": "5fb56d5e734b7e04b9c97c9d",
"creationDate": "18/11/2020",
"startTime": "10:00",
"duration": "15:00",
"voltage": "220V",
"avgPower": "34W",
"maxPower": "7200W",
"WaterConsumption": "30",
"avgTemperature": "42",
"maxTemperature": "48",
"shower": "5fb56ce7734b7e04b9c97c9b",
"__v": 0,
"id": "5fb56d5e734b7e04b9c97c9d"
},
]
}
我有三個像這樣的對象,我只想將它們從小到大排序。
我試圖將代碼更改為
{this.state.measure.map((data, index)=> {
let time = parseFloat(data.duration)
console.log(time)
})}
現在我收到 15、12、50、17.1
因為時間格式是字符串並且有:在使用 parseFloat 之前只做 time.split(':').join('.')
this.state.measure.map((data, index) => {
let time = data.duration
const totalTime = time.sort((a, b) => parseFloat(a.time.split(':').join('.') )- parseFloat(b.time.split(':').join('.')))
console.log(totalTime)
})
您應該改為對measures
數組進行排序。
this.state.measure.sort((a,b)=>{
const [m, s] = a.time.split(":").map(Number), [m2, s2] = b.time.split(":").map(Number);
return m * 60 + s - (m2 * 60 + s2);
});
如果我沒有錯,那么您想要這樣的東西-
const data = { "measures": [ { "_id": "5fbaaa", "duration": "15:00", }, { "_id": "5fbbdd", "duration": "12:20", }, { "_id": "5fbbbb", "duration": "12:00", }, { "_id": "5fbccc", "duration": "25:30", }, ] }; const inMin = (duration) => { const [hour, min] = duration.split(':'); return hour * 60 + min * 1; } data.measures.sort((a, b) => { return inMin(b.duration) - inMin(a.duration); }); console.log(data);
在這里,我縮短了您的數據結構,並假設您的持續時間為HH:mm
格式,並以分鍾為單位轉換持續時間並按desc
順序排序。
好的,聽起來你想對數組進行排序。 為此,您應該使用Array.sort
方法而不是Array.map
。
以下代碼將對比較duration
值的數組進行排序。 String.localeCompare是一個方便的 function ,因為它已經為您轉換了日期。
this.state.measures.sort((a,b) => a.duration.localeCompare(b.duration))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.