Introduction
There are some cases of processing elements in Array
. Basically solution is process with for
.
Actually, there are other solutions without using for
. Them can reduce code and keep code in simple.
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array
Tutorial - Arrow function expressions
These codes will be take same behavior.
function (e) {
return e*2;
}
e => { return e*2; }
// if one liner with return, write without return
e => e*2
By using =>
, you can omit function
, {}
and return
.
Do some processes to each elements in an Array
E.g. multiplex x2
const input = [1, 2, 3, 4];
const output = [];
for(let i = 0; i < input.length; i++) {
output.push(input[i] * 2);
}
// output: [2, 4, 6, 8]
const input = [1, 2, 3, 4];
const output = input.map(e => e*2);
// output: [2, 4, 6, 8]
Other example: Extract elements from objects in Array
const files = document.getElementById(“any-input-element”).files
const files_name = Array.from(files).map(e => e.name)
// ~~~~~~~~~~~~~~~~~
// Convert to Array from FileList
Actually, Array.from()
also has same feature of .map()
.
const files_name = Array.from(files, e => e.name);
It can be able to use .map()
to array-like object.
Extract elements what match to a condition
E.g. Extract even numbers from Array
const array = [1, 2, 3, 4];
const array_use = [];
for(let i = 0; i < array.length; i++) {
if((array[i] % 2) == 0) {
array_use.push(array[i]);
}
}
const array = [1, 2, 3, 4];
const array_use = array.filter(e => (e % 2) == 0);
Check is a value in Array
E.g. Check is input string ‘caution’, ‘warn’ or ‘danger’
const input = "warn";
const true_cases = ["warn", "danger"];
for(let i = 0; i < true_cases.length; i++) {
if(input === true_cases[i]) {
// Process for correct
}
}
const input = "warn";
// For only few true cases (about 1 or 2), this solution may be the best
if(input === “caution” || input === "warn" || input === "danger") {
// Process for valid case
} else {
// Process for invalid case
}
const input = "warn";
const true_cases = ["warn", "danger"];
if(true_cases.includes(input)) {
// Process for valid case
} else {
// Process for invalid case
}
Conclusion
Sometimes let’s see documentation (language reference, command help and so on).
You may find good functions, methods or options.
Top comments (0)