Item Index in OrderedMap

As indicated in the header, I want to get the index of a specific item. Is there any way to do this?

const key = 1
const map = new Immutable.OrderedMap([5, 'a'], [3, 'b'], [1, 'c'])

So, in this case the index keywill be 2.

+4
source share
2 answers

You can get the key sequence from the map:

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

See the docs for more details .

In addition, you can 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;
}
+3
source

the best way to do this is the way that immutablejs inners do it.

Like this:

const index = orderedMap._map.get(k);

https://github.com/facebook/immutable-js/blob/master/src/OrderedMap.js#L43

+2
source

Source: https://habr.com/ru/post/1606859/


All Articles