As the title states, I want to get the index of a particular item. Is there a way to do this?
const key = 1
const map = new Immutable.OrderedMap([5, 'a'], [3, 'b'], [1, 'c'])
So, in this case, the index of key
would be 2
.
As the title states, I want to get the index of a particular item. Is there a way to do this?
const key = 1
const map = new Immutable.OrderedMap([5, 'a'], [3, 'b'], [1, 'c'])
So, in this case, the index of key
would be 2
.
You can get the key sequence from the map:
let index = map.keySeq().findIndex(k => k === key);
Alternatively, you could explicitly iterate over the keys and compare them:
function findIndexOfKey(map, key) {
let index = -1;
for (let k of map.keys()) {
index += 1;
if (k === key) {
break
}
}
return index;
}
the best way to do it would be the way immutablejs inners does it.
Like this:
const index = orderedMap._map.get(k);
https://github.com/facebook/immutable-js/blob/master/src/OrderedMap.js#L43
let map = new Immutable.OrderedMap([["a", 1], ["b", 2]]); map.remove("a")._map.get("b") # 1
. Also, it's using non-documented internals, which can be problematic. It's a pity, because that was O(1) instead of O(n) of findIndex
. –
Interchange If you need the key and value as well as the index, you can iterate over the entrySeq
orderedMap.entrySeq().forEach((tuple,i) => console.log(`Index ${i} \n Key ${tuple[0]} \n Value ${tuple[1]}`)
© 2022 - 2024 — McMap. All rights reserved.
.indexOf(key)
to be precise), but I was worried about the performance implications of this method, and wondering if there is a better way – Chemurgy