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.

3
  • 1
    Possible duplicate of Unique values in an array Commented Oct 4, 2016 at 7:26
  • and the function he did should work, whats the problem with it? Commented Oct 4, 2016 at 7:26
  • @AhmerSaeed — PHP is not tagged! Commented Oct 4, 2016 at 7:28

4 Answers 4

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

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

Comments

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/

Comments

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

Comments

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

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.