Categories
JavaScript Answers

How to move an item of an array to the front with JavaScript?

Spread the love

To move an item of an array to the front with JavaScript, we can use the spread operator.

For instance, we write

const data = ["email", "role", "type", "name"];

const newData = [
  data.find((item) => item === "role"),
  ...data.filter((item) => item !== "role"),
];

to call data.find to find the value equals to 'role' and put it in front of the array.

Then we call data.filter to get the rest of the items in an array and spread them at the end of the array.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *