Categories
JavaScript Answers

How to remove first element from an array in JavaScript?

To remove element from an array in JavaScript, we use the shift method.

For instance, we write

const array = [1, 2, 3, 4, 5];
array.shift();

to call array.shift to remove the first element of array in place.

Categories
JavaScript Answers

How to get the first element of an array with JavaScript?

To get the first element of an array with JavaScript, we use index 0.

For instance, we write

const array = ["first", "second", "third", "fourth", "fifth"];
alert(array[0]);

to get the first entry of array with array[0].

Categories
JavaScript Answers

How to sort an array without mutating the original array with JavaScript?

To sort an array without mutating the original array with JavaScript, we make a copy of the original array.

For instance, we write

const sorted = [...arr].sort();

to make a copy of arr with the spread operator.

And then we call sort to sort the copied array.

Categories
JavaScript Answers

How to remove array element based on object property with JavaScript?

To remove array element based on object property with JavaScript, we use the filter method.

For instance, we write

const newArray = myArray.filter((obj) => {
  return obj.field !== "money";
});

to call myArray.filter with a callback that return an array with objects that has the field property not equal to 'money'.

Categories
JavaScript Answers

How to convert an object to an array of key-value pairs in JavaScript?

To convert an object to an array of key-value pairs in JavaScript, we call the Object.entries method.

For instance, we write

const obj = { 1: 5, 2: 7, 3: 0, 4: 0, 5: 0, 6: 0 };
const result = Object.entries(obj);

console.log(result);

to call Object.entries with obj to return an array with array of key-value pairs in obj.