The index of an item in OrderedMap
Asked Answered
C

3

7

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.

Chemurgy answered 10/9, 2015 at 20:27 Comment(0)
W
6

You can get the key sequence from the map:

let index = map.keySeq().findIndex(k => k === key);

See the docs for more info.

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;
}
Wahl answered 10/9, 2015 at 20:36 Comment(2)
That's what I'm doing right now (.indexOf(key) to be precise), but I was worried about the performance implications of this method, and wondering if there is a better wayChemurgy
Well, since OrderedMap doesn't provide a method to get the index itself, you have to find another way. AFAIK sequences are lazy, so it's probably equivalent to a simple loop. Provided an alternative either way.Wahl
E
3

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

Eltonelucidate answered 14/4, 2017 at 10:58 Comment(1)
Problem: When keys are removed from a map, indexes are not updated: 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
I
0

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]}`)
Innate answered 1/11, 2019 at 19:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.