Categories
JavaScript Answers

How to move item in array to last position with JavaScript?

To move item in array to last position with JavaScript, we use the splice method.

For instance, we write

const a = [1, 2, 5, 4, 3];
a.splice(4, 0, a.splice(2, 1)[0]);
console.log(a);

to remove the 3rd element from the array and return it in an array with a.splice(2, 1).

We get the removed item with index 0.

And then we put it after index 4 by calling splice again with 4, 0, and a.splice(2, 1)[0].

Categories
JavaScript Answers

How to delete property from spread operator with JavaScript?

To delete property from spread operator with JavaScript, we use the rest syntax.

For instance, we write

const myObject = {
  a: 1,
  b: 2,
  c: 3,
};
const { b, ...noB } = myObject;
console.log(noB);

to use the rest syntax to get all the properties except b from myObject.

b is destructured earlier, so it’ll be omitted from noB.

Categories
JavaScript Answers

How to create an associative array in JavaScript literal notation?

To create an associative array in JavaScript literal notation, we can create a map.

For instance, we write

const arr = new Map([
  ["key1", "User"],
  ["key2", "Guest"],
  ["key3", "Admin"],
]);

const res = arr.get("key2");
console.log(res);

to create an associative array with the Map constructor.

Then we call get with the key to get the value associated with the key.

Categories
JavaScript Answers

How to get the length of a JavaScript associative array?

To get the length of a JavaScript associative array, we use the Object.keys method.

For instance, we write

const quesArr = {};
quesArr["q101"] = "Your name?";
quesArr["q102"] = "Your age?";
quesArr["q103"] = "Your school?";
console.log(Object.keys(quesArr).length);

to call Object.keys to get the property keys of quesArr in an array.

Then we use the array’s length property to get the length of the associative array.

Categories
JavaScript Answers

How to add items to an object with JavaScript?

To add items to an object with JavaScript, we assign the value to a property.

For instance, we write

const sendData = { field1: value1, field2: value2 };

sendData.field3 = value3;

to define the sendData object.

And then we set the field3 property to value3.