Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
62
rated 0 times [  63] [ 1]  / answers: 1 / hits: 159529  / 10 Years ago, wed, may 28, 2014, 12:00:00

I want to check if an array contains role. If it does, I want to move the role to the front of the array.



var data= [email,role,type,name];
if (role in data) data.remove(data.indexOf(role)); data.unshift(role)
data;


Here, I got the result:



[role, email, role, type, name]



How can I fix this?


More From » arrays

 Answers
8

You can sort the array and specify that the value role comes before all other values, and that all other values are equal:



var first = role;
data.sort(function(x,y){ return x == first ? -1 : y == first ? 1 : 0; });


Demo: http://jsfiddle.net/Guffa/7ST24/


[#70817] Tuesday, May 27, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
pierceabnerc

Total Points: 430
Total Questions: 92
Total Answers: 102

Location: Faroe Islands
Member since Thu, Apr 8, 2021
3 Years ago
;