我有一個物件串列來存盤索引,就像這樣:
const initialIndexes = {
0: [0,1,2],
1: [0,1]
}
此時我有一個highlightedResultIndex變數。它給出了這樣的索引:
highlightedResultIndex = 0 - case 1
highlightedResultIndex = 4 - case 2
highlightedResultIndex = 2 - case 3
...
我終于嘗試通過以下結果獲得以下結果highlightedResultIndex
For the case 1:
result = {
0: 0, // index from initialIndexes
1: -1
}
For the case 2:
result = {
0: -1,
1: 1 // index from initialIndexes
}
For the case 3:
result = {
0: 2 // index from initialIndexes
1: -1
}
也許有一個簡單的方法,或者可能有某種演算法,但我不知道如何研究它,所以我想在這里寫它。如果你能幫忙,我會很高興。
編輯:
讓我在這里舉一些例子
// This is data from the server side.
const initialIndexes = {
0: [0,1,2,3],
1: [0,1,2],
2: [0,1,2],
3: [0,1,2,3,4]
}
// So, I need to index object like this by highlightedResultIndex variable
// highlightedResultIndex = 0
{
0:0,
1:-1,
2:-1,
3:-1
}
// highlightedResultIndex = 6
{
0: -1,
1:2,
2:-1,
3:-1
}
// highlightedResultIndex = 10
{
0: -1,
1:-1,
2:-1,
3:0
}
uj5u.com熱心網友回復:
您可以獲取所需的索引值并將其減少陣列的長度,直到它適合陣列。
const
initialIndexes = { 0: [0, 1, 2, 3], 1: [0, 1, 2], 2: [0, 1, 2], 3: [0, 1, 2, 3, 4] },
getIndices = n => Object.fromEntries(Object
.entries(initialIndexes)
.map(([key, array]) => {
const value = n >= 0 && n < array.length
? array[n] // or just n
: -1;
n -= array.length;
return [key, value];
})
);
console.log(getIndices(0)); // { 0: 0, 1: -1, 2: -1, 3: -1 }
console.log(getIndices(6)); // { 0: -1, 1: 2, 2: -1, 3: -1 }
console.log(getIndices(10)); // { 0: -1, 1: -1, 2: -1, 3: 0 }
.as-console-wrapper { max-height: 100% !important; top: 0; }
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/437294.html
標籤:javascript 算法
上一篇:查找陣列的連續元素之間的最大差異
下一篇:空間成本最小化演算法的最佳設計
