Categories
JavaScript Answers

How to move an array element from one array position to another with JavaScript?

To move an array element from one array position to another with JavaScript, we use the splice method.

For instance, we write

const arrayMove = (arr, fromIndex, toIndex) => {
  const element = arr[fromIndex];
  arr.splice(fromIndex, 1);
  arr.splice(toIndex, 0, element);
};

to define the arrayMove method.

We get the element at fromIndex with arr[fromIndex].

Then we call arr.splice with fromIndex and 1 to remove the item at fromIndex.

Then we insert the element at toIndex by calling splice with toIndex, 0, and element.

Categories
JavaScript Answers

How to find if an array contains a specific string in JavaScript?

To find if an array contains a specific string in JavaScript, we use the includes method.

For instance, we write

const found = categories.includes("foo");

to check of 'foo' is in the categories array with categories.includes.

Categories
JavaScript Answers

How to convert a set to an array with JavaScript?

To convert a set to an array with JavaScript, we use the spread operator.

For instance, we write

const array = [...mySet];

to use the spread operator to convert the mySet set to an array.

Categories
JavaScript Answers

How to get distinct values from an array of objects in JavaScript?

To get distinct values from an array of objects in JavaScript, we convert the objects to JSON strings and put them in a set.

For instance, we write

const things = [];
things.push({ place: "here", name: "stuff" });
things.push({ place: "there", name: "morestuff" });
things.push({ place: "there", name: "morestuff" });

const newThings = Array.from(new Set(myData.map(JSON.stringify))).map(
  JSON.parse
);

to call myData.map with JSON.stringify to return an array of JSON strings converted from the objects in the things array.

And then we convert the array to a set with Set to remove the duplicate strings.

Next we call Array.from to convert the set back to an array.

And then we call map with JSON.parse to convert the JSON strings back to objects.

Categories
JavaScript Answers

How to convert array to object with JavaScript?

To convert array to object with JavaScript, we use the Object.entries and Object.fromEntries methods.

For instance, we write

const arr = ["a", "b", "c"];
const obj = Object.fromEntries(Object.entries(arr));

to call Object.entries with arr to convert arr to an array of key-value pair arrays with the index as the key and the element as the value.

Then we call Object.fromEntries to convert the array to an object with the key as the property key and the values as the property values.