'How to get index based value from Set

I am looking to store a list of unique string (hence Set) and wanted to retrieve the value based on the index. I used get(index) But it turned out it returns undefined. So it seems I did not understand Set well.

In case value needed to be retrieved do we have to convert it back to the array and then only read it or with "get(index)" it can be achieved?

Also, I have checked Set tests to understand get(index) but still not clear.

const { Set } = require('immutable');

const set = Set(["ab", "cd", "ef"])
console.log(set.get(1)) //logs undefined
console.log(set.toJS()[1]) //logs "cd"


Solution 1:[1]

Another way to do that would be to use Array.from(set)[0].

Solution 2:[2]

Here I'm trying to using the Set in es2015 directly without ImmutableJS:

You could write customized function like this:

Set.prototype.getByIndex = function(index) { return [...this][index]; }

var set = new Set(['a', 'b', 'c'])

console.log(set.getByIndex(0))  // 'a'

Note that the spread operator converts a set to an array so that you can use index to get access to the element

Solution 3:[3]

the way to use Immutable's get is by "key" not by index

console.log(set.get("cd")) // logs cd, at index 1

if you want to get an element from the Set's iterator, you have to extend Immutable's Set

Set.prototype.getByIdx = function(idx){
  if(typeof idx !== 'number') throw new TypeError(`Argument idx must be a Number. Got [${idx}]`);

  let i = 0;
  for( let iter = this.keys(), curs = iter.next(); !curs.done; curs = iter.next(), i++ )
    if(idx === i) return curs.value;

  throw new RangeError(`Index [${idx}] is out of range [0-${i-1}]`);
}

const set = Set(["ab", "cd", "ef"]);

console.log(set.getByIdx(1)) //logs cd

Solution 4:[4]

let data = new Set();
data.add('Value 1');
data.add('Value 2');
data.add('Value 3');

function getSetValueByIndex(setObj, index) {
    return [...setObj][index]
}
console.log(getSetValueByIndex(data, 1))

Solution 5:[5]

Using Array.from() or spread requires iterating the entire set before returning an example. This is not ideal from a performance perspective.

A better solution would be:

function getSetValueByIndex(target, index) { 
  if (typeof index !== 'number') throw new Error(`Index must be a number!`);

  let i = 0;
  for (const item of target) if (i++ === index) return item;

  throw new Error(`Index ${index} out of bounds!`);
}

Solution 6:[6]

I find myself using an Array with another Set to check if I should put the new Value into the Array

example:

let myArray = [1,2,3,4]
let check = new Set(myArray)

function PushToArray( newValue ){
  if( !check.has(newValue) )
   myArray.push(newValue)
   check.add(newValue)
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 user1514042
Solution 2 Chang
Solution 3 theRemix
Solution 4 Emin AdiloÄŸlu
Solution 5
Solution 6