Javascript Data Type How to - Sort array to Move an item of an array to the front








Question

We would like to know how to sort array to Move an item of an array to the front.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
<!--from ww  w  .ja  va  2  s.c o m-->
var data= ["email","role","type","name"];
var first = "role";
data.sort(function(x,y){ return x == first ? -1 : y == first ? 1 : 0; });
document.writeln(data);

</script>
</head>
<body>
</body>
</html>

The code above is rendered as follows: