1

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']
1
  • 3
    If the element is already in the set, do you want the old one to stay where it is, or get moved to the front? Commented Mar 31, 2017 at 20:13

2 Answers 2

4

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]);

Sign up to request clarification or add additional context in comments.

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.