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.

Categories
JavaScript Answers

How to add values to an array of objects dynamically in JavaScript?

To add values to an array of objects dynamically in JavaScript, we use the spread syntax.

For instance, we write

let data = [
  { label: "1", value: 12 },
  { label: "1", value: 12 },
  { label: "1", value: 12 },
];

data = [...data, { label: "2", value: 14 }];

to spread the entries in data with ... into a new array.

And then we add another object at the end of the new array.

We then assign the new array as the value of data.

Categories
JavaScript Answers

How to use array reduce with condition in JavaScript?

To use array reduce with condition in JavaScript, we call filter to return a filtered array.

For instance, we write

const sum = records
  .filter(({ gender }) => gender === "male")
  .reduce((sum, record) => sum + record.value);

to call recorda.filter to return an array where the gender property in the object in the array is 'male'.

Then we call reduce with a callback to return the sum of the partial sum sum and record.value.