Naj
Naj

Reputation: 853

Javascript Set ES6

Is there a way to insert an item as first element of Set in javascript like it is done in arrays in the example below ?

arr['a','b','c']
arr.unshift ('d')
//Result
arr['d','a','b','c']

Upvotes: 1

Views: 195

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386600

There is no direct way, or a method to unshift a set element.

You could use the spread syntax ... for the old set and generate a new set.

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

mySet = new Set(['d', ...mySet]);

console.log([...mySet]);

Upvotes: 4

Mike Cluck
Mike Cluck

Reputation: 32511

The order of a Set is determined by when the items are inserted. Depending on what you want to do you can either insert items into a Set then extract those values and sort as needed or you can insert them into an array in the correct order then create a Set from that array.

let standardSet = new Set();
standardSet.add('c');
standardSet.add('a');
standardSet.add('b');
let fromStandard = Array.from(standardSet);
fromStandard.sort();
console.log(fromStandard);

let arr = [];
arr.unshift('c');
arr.unshift('b');
arr.unshift('a');
let fromArr = Array.from(new Set(arr));
console.log(fromArr);

Upvotes: 0

Related Questions