0

I'm trying to find an element in an array, remove that element if found, and then add that element at the start of the array.

However when I log my array sortedAdv returns as only one element length for some reason

My code:

let advantages = [ 'liked', 'sendUnlimitedLikes', 'unlockSundays', 'getBoosted', 'filters', 'revealAllProfiles', 'wholeCountry', 'exlusiveBlogs' ];
 
console.log('advantages', advantages.length);

let index = advantages.findIndex((advantage) => advantage == type);
if (index > -1) {
  console.log('index', index);
  let sortedAdv = advantages.splice(index, 1);
  console.log('sortedAdv', sortedAdv.length);
  sortedAdv.unshift(type);
  console.log('sortedAdv', sortedAdv.length);
  this.setPurchaseAdvantages(sortedAdv);
}
pilchard
  • 12,414
  • 5
  • 11
  • 23
gabogabans
  • 3,035
  • 5
  • 33
  • 81
  • splice returns the removed elements, not the original array. – pilchard Jun 05 '23 at 23:07
  • Does this answer your question? [Move element to first position in array](https://stackoverflow.com/questions/50186075/move-element-to-first-position-in-array) – pilchard Jun 05 '23 at 23:09
  • also [Move an array element from one array position to another](https://stackoverflow.com/questions/5306680/move-an-array-element-from-one-array-position-to-another) – pilchard Jun 05 '23 at 23:09

1 Answers1

0

you are geting an array when you are using this

let removedElement = advantages.splice(index, 1);
let advantages = ['liked', 'sendUnlimitedLikes', 'unlockSundays', 'getBoosted', 'filters', 'revealAllProfiles', 'wholeCountry', 'exlusiveBlogs'];
let type = 'getBoosted'; 
let index = advantages.indexOf(type); // Find the index of the element
if (index > -1) {
  let removedElement = advantages.splice(index, 1)[0]; // Remove the element and store it
  advantages.unshift(removedElement); // Add the element to the start of the array
}

console.log(advantages);
Veer Pratap
  • 118
  • 2
  • 11