Categories
JavaScript Answers

How to delete an item from Redux state with JavaScript?

To delete an item from Redux state with JavaScript, we can use the array filter method.

For instance, we write

export const commentList = (state, action) => {
  switch (action.type) {
    //...
    case "DELETE_COMMENT":
      return state.filter(({ id }) => id !== action.data);
    //...
  }
};

to call state.filter to return an array without the object with the id property equal the action.data property.

The returned array will be the new value of the state.

Categories
JavaScript Answers

How to add spaces between array items in JavaScript?

To add spaces between array items in JavaScript, we use the join method.

For instance, we write

const showtimes = ["1pm", "2pm", "3pm"];
const showtimesAsString = showtimes.join(", ");

to call showtimes.join with ', ' as the delimiter between each string in showtimes.

Therefore, showtimesAsString is "1pm, 2pm, 3pm".

Categories
JavaScript Answers

How to find missing numbers in a sequence with JavaScript?

To find missing numbers in a sequence with JavaScript, we use a for loop.

For instance, we write

for (let i = 1; i < numArray.length; i++) {
  if (numArray[i] - numArray[i - 1] !== 1) {
    //...
  }
}

to loop through the sorted array numArray with a for loop.

In it, we check if the current number being looped through numArray[i] is 1 less than the previous number numArray[i - 1] by subtracting them and see if the difference is 1.

If it’s not, then the numbers in between the 2 numbers are missing.

Categories
JavaScript Answers

How to convert string to array of object in JavaScript?

To convert string to array of object in JavaScript, we use the JSON.parse method.

For instance, we write

const jsonString = '{ "a": 1, "b": 2 }';
const myObject = JSON.parse(jsonString);

to call JSON.parse with jsonString to convert jsonString into an object.

Categories
JavaScript Answers

How to array push key value with JavaScript?

To array push key value with JavaScript, we call the push method.

For instance, we write

const arr = ["left", "top"];
const x = [];

for (const a of arr) {
  x.push({
    [a]: 0,
  });
}

to loop through the arr array with a for-of loop.

Then we call x.push with an object with key a and value 0.

a is the value being looped through in arr.