Categories
JavaScript Answers

How to create a fixed length array in JavaScript?

To create a fixed length array in JavaScript, we call the Object.seal method.

For instance, we write

const a = new Array(100);
a.fill(undefined);
Object.seal(a);

to create array a with length 100.

Then we call fill with undefined to fill all empty slots with undefined.

We need to fill the empty slots since they can’t be changed after seal is called.

Then we call Object.seal to seal array a to keep its length from changing.

Categories
JavaScript Answers

How to sum two arrays in single iteration with JavaScript?

To sum two arrays in single iteration with JavaScript, we use the map method.

For instance, we write

const array1 = [1, 2, 3, 4];
const array2 = [5, 6, 7, 8];

const sum = array1.map((num, idx) => {
  return num + array2[idx];
});

to call array1.map with a callback that returns the sum of num and item in array2 at the same idx index.

The array with the sums is returned.

Categories
JavaScript Answers

How to search for a string inside an array of strings with JavaScript?

To search for a string inside an array of strings with JavaScript, we use the find method.

For instance, we write

const strs = ["abc", "def", "ghi", "jkl", "mno"];
const value = "abc";
const str = strs.find((str) => str === value);

to call strs.find with a callback that checks if str in strs is equal to value.

If there is such an entry, then the first instance of str is returned.

Categories
JavaScript Answers

How to get the size of an array in an object with JavaScript?

To get the size of an array in an object with JavaScript, we use the length property.

For instance, we write

const st = {
  itemA: {},
  itemB: [
    { id: "s01", cd: "c01", dd: "d01" },
    { id: "s02", cd: "c02", dd: "d02" },
  ],
};

console.log(st.itemB.length);

to get the length of the st.itemB array property with st.itemB.length.

Categories
JavaScript Answers

How to find length or size of an array in JavaScript?

To find length or size of an array in JavaScript, we use the length property.

For instance, we write

const arr = [];
arr[1] = 2;
arr[2] = 3;
console.log(arr.length);

to create the array arr.

Then we get its size with arr.length.