JS Reference
Service Workers
ESModule Tips
NodeJS Tips
Javascript Tutorial
Javascript Arrays
How to process content of Arrays in different ways
Array Length
Length Property and Not a Method
- Array length is a property array.length
- Array length is not a method
array.length() - Data Type: It is an unsigned, 32-bit integer with a maximum value of 232 - 1 (Max: 4,294,967,295)
- Non-Numeric Indices: Adding properties to an array using strings
- e.g.: arr["sample"] = "NewValue"
- treated as object properties
- does not affect the length property
Array resize using array.length
- Array can be resized by assigning value to the length property array.length = array.length + 3
- Assigning lesser value than the actual length will make the array shorter array.length = array.length - 3
- Setting array.length = 0 will clear the array and make it zero length, empty array.
- Negative value or a non-integer to length array.length = -3 will throw "RangeError"
Array Length
script.js
const data = ['first', 'second', 'third'];
console.log(data.length); // Output: 3
Array shorten
script.js
const data = ['first', 'second', 'third'];
data.length = 2;
console.log(data); // Output: ['first', 'second'];
Last Element
script.js
const data = ['first', 'second', 'third'];
console.log(data[length-1]); // Output: third
Remove empty string or falsey from an Array
To remove empty string or falsey values from an array, filter option could be used.
Filter Array with empty string ""
- If only empty string literals ("") are to be removed
- This will keep other values like 0 or null
Sample Code
script.js
let data = ["first", "", "third", "", "fifth"];
const newData = data.filter(item => item !== "");
//const newData = data.filter((item) => { return item !== ""});
console.log(newData) // Output: ["first", "third", "fifth"]
Filter Array all Falsey values
- It removes "" , null , undefined , 0 , false and NaN
Sample Code
script.js
let data = ["first", "", "third", "", "fifth"];
const newData = data.filter(Boolean);
console.log(newData) // Output: ["first", "third", "fifth"]
Array - check elements
Check "Every" array elements
Check each array element follows certain logic.
Sample Code
script.js
const data = [1, 2, 3, 4];
// Check if all numbers are greater than 0
// const output = data.every(element => element > 5);
const output = data.every((element,index,array) => {
return element > 0
});
console.log(output); // true
Check if "Some" array elements follow the rule
Check if at least one array element follows the rule.
Sample Code
script.js
const data = [-1, -2, 1, 2, 3, 4];
// Check if all numbers are greater than 0
// const output = data.some(element => element > 5);
const output = data.some((element,index,array) => {
return element > 0
});
console.log(output); // true