Categories
JavaScript Answers

How to copy all items from one array into another with JavaScript?

To copy all items from one array into another with JavaScript, we use the spread operator.

For instance, we write

const objArray = [
  { name: "first" },
  { name: "second" },
  { name: "third" },
  { name: "fourth" },
];
const clonedArr = [...objArray];

to use the spread operator to spread the objArray entries into a new array by copying each entry.

Categories
JavaScript Answers

How to print object array in JavaScript?

To print object array in JavaScript, we call the JSON.stringify method.

For instance, we write

const lineChartData = [
  {
    date: new Date(2022, 10, 2),
    value: 5,
  },
  {
    date: new Date(2022, 10, 25),
    value: 30,
  },
  {
    date: new Date(2022, 10, 26),
    value: 72,
    customBullet: "images/redstar.png",
  },
];

document.getElementById("whereToPrint").innerHTML = JSON.stringify(
  lineChartData,
  null,
  2
);

to call JSON.stringify to convert the lineChartData array into a JSON string with each level indented with 2 spaces.

Then we set that as the value of the element’s innerHTML property to render the JSON string in the element as its content.

Categories
JavaScript Answers

How to iterate array keys in JavaScript?

To iterate array keys in JavaScript, we use the Object.keys method to get an array of string keys from the array.

For instance, we write

const array = [];
widthRange[46] = { sel: 46, min: 0, max: 52 };
widthRange[66] = { sel: 66, min: 52, max: 70 };
widthRange[90] = { sel: 90, min: 70, max: 94 };
const keys = Object.keys(array);

to call Object.keys with array to return an array of indexes of the array array.

Categories
JavaScript Answers

How to get the second to last item of an array with JavaScript?

To get the second to last item of an array with JavaScript, we use the length subtract by 2 index.

For instance, we write

const pgUrl = array[array.length - 2];

to get the 2nd last item in array with index array.length - 2.

Categories
JavaScript Answers

How to split string with white space with JavaScript?

To split string with white space with JavaScript, we use the split method.

For instance, we write

const str = "my car is green";
const stringArray = str.split(/(\s+)/);

to call str.split with a regex that matches whitespaces to split the str string by the whitespaces and return an array with the split substrings.