1

I have an array (or Set?) of arr = ['a', 'b', 'c'] and I want to add d to it, which could be done with arr.push('d').

But I only want unique values in the array, and I want the latest values added to be in the front of the array.

So if I first add d the array should become ['d', 'a', 'b', 'c'] and if I now add b the array should become ['b', 'd', 'a', 'c'] etc.

Should it be something like

function addElement(arr, element) {
  if (arr.includes(element)) {
    arr.splice(arr.indexOf(element, 1));
  }
  arr.unshift(element);
}

I guess this could be done with Sets, since sets can only contain unique values.

Chris Charles
  • 4,406
  • 17
  • 31
mortensen
  • 1,167
  • 2
  • 13
  • 23

4 Answers4

2

You could use a Set and delete the item in advance and add it then. To get the wanted order, you need to reverse the rendered array.

function addToSet(v, set) {
    set.delete(v);
    set.add(v);
}

var set = new Set;

addToSet('d', set);
addToSet('c', set);
addToSet('b', set),
addToSet('a', set);
addToSet('d', set);

console.log([...set].reverse());
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0
var  val = 'c';
var arr = ['a','b'];
if($.inArray( val, arr ) ==-1){
// value dosend exit    
    arr.unshift(val);
} else {
    console.log('value already there')
}
console.log(arr);

$.inArray() work similar to indexOf() method. It searches the element in an array, if it’s found then it return it’s index.

http://webrewrite.com/check-value-exist-array-javascriptjquery/

channasmcs
  • 1,104
  • 12
  • 27
0

your function works just you have to adjust with a small fix

 arr.splice(arr.indexOf(element),1);

var arr = ['a', 'b', 'c'] ;

function addElement(arr, element) {
  if (arr.includes(element)) {
    arr.splice(arr.indexOf(element),1);
  }
  arr.unshift(element);
}
addElement(arr,'d');
addElement(arr,'b');
console.log(arr);
Vladu Ionut
  • 8,075
  • 1
  • 19
  • 30
0

Especially for those who don't like .unshift() performance This would be another way of doing this job;

function funky(a,e){
  var ix = a.indexOf(e);
  return (~ix ? a.splice(ix,0,...a.splice(0,ix))
              : a.splice(0,0,e),a);
}
var a = ['d', 'a', 'b', 'c'];

console.log(funky(a,'z'));
console.log(funky(a,'d'));
console.log(funky(a,'c'));
console.log(funky(a,'f'));
Redu
  • 25,060
  • 6
  • 56
  • 76