JavaScript Course 5: Arrays: Difference between revisions

From WikiMLT
m (Стадий: 6 [Фаза:Утвърждаване, Статус:Утвърден]; Категория:JavaScript)
 
m (Text replacement - "mlw-continue" to "code-continue")
 
Line 18: Line 18:
In JavaScript, the Arrays are kind of objects, so the are a couple of built-in properties [like <code>.length</code>] and methods [like <code>.indexOf()</code>].
In JavaScript, the Arrays are kind of objects, so the are a couple of built-in properties [like <code>.length</code>] and methods [like <code>.indexOf()</code>].


Remember the index of the Arrays starts from <code>0</code>.<syntaxhighlight lang="text" class="mlw-continue">
Remember the index of the Arrays starts from <code>0</code>.<syntaxhighlight lang="text" class="code-continue">
[1, 2, 3, 1, 4]
[1, 2, 3, 1, 4]
  0  1  2  3  4
  0  1  2  3  4
Line 25: Line 25:
== Adding Elements to an Array ==
== Adding Elements to an Array ==
'''Add elements to the end''' of an Array by using <code>[https://www.w3schools.com/jsref/jsref_push.asp .push(elements)]</code> method. It adds new items to the end of an array, changes the length of the array, returns the new length.
'''Add elements to the end''' of an Array by using <code>[https://www.w3schools.com/jsref/jsref_push.asp .push(elements)]</code> method. It adds new items to the end of an array, changes the length of the array, returns the new length.
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
numbers.push(5, 6);
numbers.push(5, 6);
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
console.log(numbers);
console.log(numbers);
</syntaxhighlight>
</syntaxhighlight>
Line 35: Line 35:
</syntaxhighlight>
</syntaxhighlight>
'''Add elements to the beginning''' of an Array by using <code>[https://www.w3schools.com/jsref/jsref_unshift.asp .unshift(elements)]</code> method. It  adds new elements to the beginning of an array, overwrites the original array.
'''Add elements to the beginning''' of an Array by using <code>[https://www.w3schools.com/jsref/jsref_unshift.asp .unshift(elements)]</code> method. It  adds new elements to the beginning of an array, overwrites the original array.
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
numbers.unshift(1, 2);
numbers.unshift(1, 2);
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
console.log(numbers);
console.log(numbers);
</syntaxhighlight>
</syntaxhighlight>
Line 45: Line 45:
</syntaxhighlight>
</syntaxhighlight>
'''Add elements to the middle''' of an Array by using <code>[https://www.w3schools.com/jsref/jsref_splice.asp .splice(index, delete count, elements to add)]</code> method.  It adds and/or removes array elements, overwrites the original array.  
'''Add elements to the middle''' of an Array by using <code>[https://www.w3schools.com/jsref/jsref_splice.asp .splice(index, delete count, elements to add)]</code> method.  It adds and/or removes array elements, overwrites the original array.  
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
numbers.splice(2, 0, 'a', 'b'); // 0 means we won't remove elements
numbers.splice(2, 0, 'a', 'b'); // 0 means we won't remove elements
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
console.log(numbers);
console.log(numbers);
</syntaxhighlight>
</syntaxhighlight>
Line 57: Line 57:
== Finding Elements in an Array ==
== Finding Elements in an Array ==
=== Finding Primitive types in an Array ===
=== Finding Primitive types in an Array ===
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
const numbers = [1, 2, 3, 1, 4];
const numbers = [1, 2, 3, 1, 4];
</syntaxhighlight>By using <code>[https://www.w3schools.com/jsref/jsref_indexof_array.asp .indexOf(element, start_index=0)]</code> method we can find the first occurrence of an element.  
</syntaxhighlight>By using <code>[https://www.w3schools.com/jsref/jsref_indexof_array.asp .indexOf(element, start_index=0)]</code> method we can find the first occurrence of an element.  
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
console.log(numbers.indexOf(1));
console.log(numbers.indexOf(1));
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="shell-session">
<syntaxhighlight lang="shell-session">
0
0
</syntaxhighlight><syntaxhighlight lang="javascript" class="mlw-continue">
</syntaxhighlight><syntaxhighlight lang="javascript" class="code-continue">
console.log(numbers.indexOf(3));
console.log(numbers.indexOf(3));
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="shell-session">
<syntaxhighlight lang="shell-session">
2
2
</syntaxhighlight><syntaxhighlight lang="javascript" class="mlw-continue">
</syntaxhighlight><syntaxhighlight lang="javascript" class="code-continue">
console.log(numbers.indexOf('c')); // This element doesn't exist
console.log(numbers.indexOf('c')); // This element doesn't exist
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="shell-session">
<syntaxhighlight lang="shell-session">
-1
-1
</syntaxhighlight>By using <code>[https://www.w3schools.com/jsref/jsref_lastindexof_array.asp .lastIndexOf(element, start_index=array_lenght)]</code> method we can find the last occurrence of an element. <syntaxhighlight lang="javascript" class="mlw-continue">
</syntaxhighlight>By using <code>[https://www.w3schools.com/jsref/jsref_lastindexof_array.asp .lastIndexOf(element, start_index=array_lenght)]</code> method we can find the last occurrence of an element. <syntaxhighlight lang="javascript" class="code-continue">
console.log(numbers.latIndexOf(1));
console.log(numbers.latIndexOf(1));
</syntaxhighlight>
</syntaxhighlight>
Line 83: Line 83:


==== Test whether a given (primitive) element exists in an Array ====
==== Test whether a given (primitive) element exists in an Array ====
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
const numbers = [1, 2, 3, 1, 4];
const numbers = [1, 2, 3, 1, 4];
</syntaxhighlight>The old way, by using <code>[https://www.w3schools.com/jsref/jsref_indexof_array.asp .indexOf(element, start_index=0)]</code> method.<syntaxhighlight lang="javascript" class="mlw-continue">
</syntaxhighlight>The old way, by using <code>[https://www.w3schools.com/jsref/jsref_indexof_array.asp .indexOf(element, start_index=0)]</code> method.<syntaxhighlight lang="javascript" class="code-continue">
console.log(numbers.indexOf(1) !== -1); // will return 'true' if one or more elements with value 1 exist in the array 'numbers'
console.log(numbers.indexOf(1) !== -1); // will return 'true' if one or more elements with value 1 exist in the array 'numbers'
</syntaxhighlight><syntaxhighlight lang="javascript" class="mlw-continue">
</syntaxhighlight><syntaxhighlight lang="javascript" class="code-continue">
if (numbers.indexOf(1) !== -1) { ... }
if (numbers.indexOf(1) !== -1) { ... }
</syntaxhighlight>The modern way, by using <code>[https://www.w3schools.com/jsref/jsref_includes_array.asp .includes(element, start_index=0)]</code> method.<syntaxhighlight lang="javascript" class="mlw-continue">
</syntaxhighlight>The modern way, by using <code>[https://www.w3schools.com/jsref/jsref_includes_array.asp .includes(element, start_index=0)]</code> method.<syntaxhighlight lang="javascript" class="code-continue">
console.log(numbers.includes(1)); // will return 'true' if one or more elements with value 1 exist in the array 'numbers'
console.log(numbers.includes(1)); // will return 'true' if one or more elements with value 1 exist in the array 'numbers'
</syntaxhighlight><syntaxhighlight lang="javascript" class="mlw-continue">
</syntaxhighlight><syntaxhighlight lang="javascript" class="code-continue">
if (numbers.includes(1)) { ... }
if (numbers.includes(1)) { ... }
</syntaxhighlight>
</syntaxhighlight>
Line 97: Line 97:
==== Start Index ====
==== Start Index ====
All these methods ah a second optional parameter which is <code>start index</code>.
All these methods ah a second optional parameter which is <code>start index</code>.
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
const numbers = [1, 2, 3, 1, 4, 1, 5, 6];
const numbers = [1, 2, 3, 1, 4, 1, 5, 6];
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
console.log(numbers.length);
console.log(numbers.length);
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="shell-session">
<syntaxhighlight lang="shell-session">
8
8
</syntaxhighlight><syntaxhighlight lang="javascript" class="mlw-continue">
</syntaxhighlight><syntaxhighlight lang="javascript" class="code-continue">
console.log(numbers.indexOf(1)); // start index = 0
console.log(numbers.indexOf(1)); // start index = 0
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="shell-session">
<syntaxhighlight lang="shell-session">
0
0
</syntaxhighlight><syntaxhighlight lang="javascript" class="mlw-continue">
</syntaxhighlight><syntaxhighlight lang="javascript" class="code-continue">
console.log(numbers.indexOf(1, 2)); // start index = 2
console.log(numbers.indexOf(1, 2)); // start index = 2
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="shell-session">
<syntaxhighlight lang="shell-session">
3
3
</syntaxhighlight><syntaxhighlight lang="javascript" class="mlw-continue">
</syntaxhighlight><syntaxhighlight lang="javascript" class="code-continue">
console.log(numbers.lastIndexOf(1)); // start index = array_length, and backwods count
console.log(numbers.lastIndexOf(1)); // start index = array_length, and backwods count
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="shell-session">
<syntaxhighlight lang="shell-session">
5
5
</syntaxhighlight><syntaxhighlight lang="javascript" class="mlw-continue">
</syntaxhighlight><syntaxhighlight lang="javascript" class="code-continue">
console.log(numbers.lastIndexOf(1, 4)); // start index = 4, and backwods count
console.log(numbers.lastIndexOf(1, 4)); // start index = 4, and backwods count
</syntaxhighlight>
</syntaxhighlight>
Line 128: Line 128:


=== Finding Reference types in an Array ===
=== Finding Reference types in an Array ===
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
const courses = [
const courses = [
     {id: 1, name: 'a'},
     {id: 1, name: 'a'},
     {id: 2, name: 'b'}
     {id: 2, name: 'b'}
];
];
</syntaxhighlight>By using <code>[https://www.w3schools.com/jsref/jsref_find.asp .find(callback_fn)]</code> method we can '''find an Object''' within Array, which has a given property.<syntaxhighlight lang="javascript" class="mlw-continue">
</syntaxhighlight>By using <code>[https://www.w3schools.com/jsref/jsref_find.asp .find(callback_fn)]</code> method we can '''find an Object''' within Array, which has a given property.<syntaxhighlight lang="javascript" class="code-continue">
let course_A_exist = courses.find(function(course) {
let course_A_exist = courses.find(function(course) {
   return course.name === 'a';  
   return course.name === 'a';  
});
});
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
console.log(course_A_exist);  // will return 'undefined' if the element dosn't exist
console.log(course_A_exist);  // will return 'undefined' if the element dosn't exist
</syntaxhighlight>
</syntaxhighlight>
Line 144: Line 144:
{id: 1, name: 'a'}
{id: 1, name: 'a'}
</syntaxhighlight>
</syntaxhighlight>
By using <code>[https://www.w3schools.com/jsref/jsref_findindex.asp .findIndex(callback_fn)]</code> method we can '''find the Index of an Object''' within Array, which has a given property.<syntaxhighlight lang="javascript" class="mlw-continue">
By using <code>[https://www.w3schools.com/jsref/jsref_findindex.asp .findIndex(callback_fn)]</code> method we can '''find the Index of an Object''' within Array, which has a given property.<syntaxhighlight lang="javascript" class="code-continue">
let course_B_index = courses.findIndex(function(course) {
let course_B_index = courses.findIndex(function(course) {
   return course.name === 'b';  
   return course.name === 'b';  
});
});
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
console.log(course_B_index);  // will return '-1' if the element dosn't exist
console.log(course_B_index);  // will return '-1' if the element dosn't exist
</syntaxhighlight>
</syntaxhighlight>
Line 161: Line 161:
The initial state of the callback function.
The initial state of the callback function.
|
|
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
let course_A_exist = courses.find(function(course) {
let course_A_exist = courses.find(function(course) {
   return course.name === 'a';  
   return course.name === 'a';  
Line 171: Line 171:
Step 1, remove the ''function'' keyword, and separate the parameters of the function from its body put a ''fat arrow.''
Step 1, remove the ''function'' keyword, and separate the parameters of the function from its body put a ''fat arrow.''
|
|
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
let course_A_exist = courses.find((course) => {
let course_A_exist = courses.find((course) => {
   return course.name === 'a';  
   return course.name === 'a';  
Line 181: Line 181:
Step 2, if the function have a single parameter we can also remove the parentheses.
Step 2, if the function have a single parameter we can also remove the parentheses.
|
|
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
let course_A_exist = courses.find(course => {
let course_A_exist = courses.find(course => {
   return course.name === 'a';  
   return course.name === 'a';  
Line 187: Line 187:
</syntaxhighlight>
</syntaxhighlight>
If you do not have any parameters you have to pass empty parentheses:  
If you do not have any parameters you have to pass empty parentheses:  
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
let course_A_exist = courses.find(() => { ... });
let course_A_exist = courses.find(() => { ... });
</syntaxhighlight>
</syntaxhighlight>
Line 195: Line 195:
Step 3, if the function is a single line of code, we can make this code even shorter: 1) get rid of the <code>return</code> keyword, 2) remove the curly braces, 3) place everything on one line.
Step 3, if the function is a single line of code, we can make this code even shorter: 1) get rid of the <code>return</code> keyword, 2) remove the curly braces, 3) place everything on one line.
|
|
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
let course_A_exist = courses.find(course => course.name === 'a');
let course_A_exist = courses.find(course => course.name === 'a');
</syntaxhighlight>
</syntaxhighlight>
Line 201: Line 201:


== Removing Elements of an Array ==
== Removing Elements of an Array ==
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
const numbers = [1, 2, 3, 4, 5, 6];
const numbers = [1, 2, 3, 4, 5, 6];
</syntaxhighlight>'''Remove elements to the end''' of an Array by using <code>[https://www.w3schools.com/jsref/jsref_pop.asp .pop(elements)]</code> method. It removes (pops) the last element of an array, changes the original array, returns the removed element.<syntaxhighlight lang="javascript" class="mlw-continue">
</syntaxhighlight>'''Remove elements to the end''' of an Array by using <code>[https://www.w3schools.com/jsref/jsref_pop.asp .pop(elements)]</code> method. It removes (pops) the last element of an array, changes the original array, returns the removed element.<syntaxhighlight lang="javascript" class="code-continue">
let last = numbers.pop();
let last = numbers.pop();
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
console.log(numbers);
console.log(numbers);
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="shell-session" class="mlw-continue">
<syntaxhighlight lang="shell-session" class="code-continue">
(5) [1, 2, 3, 4, 5]
(5) [1, 2, 3, 4, 5]
</syntaxhighlight><syntaxhighlight lang="javascript" class="mlw-continue">
</syntaxhighlight><syntaxhighlight lang="javascript" class="code-continue">
console.log(last);
console.log(last);
</syntaxhighlight><syntaxhighlight lang="shell-session">
</syntaxhighlight><syntaxhighlight lang="shell-session">
Line 217: Line 217:
</syntaxhighlight>
</syntaxhighlight>


'''Remove elements to the beginning''' of an Array by using <code>[https://www.w3schools.com/jsref/jsref_shift.asp .shift(elements)]</code> method. It removes the first item of an array, changes the original array, returns the shifted element.<syntaxhighlight lang="javascript" class="mlw-continue">
'''Remove elements to the beginning''' of an Array by using <code>[https://www.w3schools.com/jsref/jsref_shift.asp .shift(elements)]</code> method. It removes the first item of an array, changes the original array, returns the shifted element.<syntaxhighlight lang="javascript" class="code-continue">
let first = numbers.shift();
let first = numbers.shift();
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
console.log(numbers);
console.log(numbers);
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="shell-session" class="mlw-continue">
<syntaxhighlight lang="shell-session" class="code-continue">
(4) [2, 3, 4, 5]
(4) [2, 3, 4, 5]
</syntaxhighlight><syntaxhighlight lang="javascript" class="mlw-continue">
</syntaxhighlight><syntaxhighlight lang="javascript" class="code-continue">
console.log(first);
console.log(first);
</syntaxhighlight><syntaxhighlight lang="shell-session">
</syntaxhighlight><syntaxhighlight lang="shell-session">
Line 232: Line 232:


'''Remove elements to the middle''' of an Array by using <code>[https://www.w3schools.com/jsref/jsref_splice.asp .splice(index, delete count, elements to add)]</code> method. It adds and/or removes array elements, overwrites the original array.
'''Remove elements to the middle''' of an Array by using <code>[https://www.w3schools.com/jsref/jsref_splice.asp .splice(index, delete count, elements to add)]</code> method. It adds and/or removes array elements, overwrites the original array.
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
numbers.splice(1, 2); // we will remove 2 elemets starting from index 1
numbers.splice(1, 2); // we will remove 2 elemets starting from index 1
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
console.log(numbers);
console.log(numbers);
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="shell-session" class="mlw-continue">
<syntaxhighlight lang="shell-session" class="code-continue">
(2) [2, 5]
(2) [2, 5]
</syntaxhighlight>
</syntaxhighlight>


== Emptying an Array ==
== Emptying an Array ==
'''1.''' Reassign to a new empty array. In this case we can't use <code>const</code> in order to define the array's memory object.<syntaxhighlight lang="javascript" class="mlw-continue">
'''1.''' Reassign to a new empty array. In this case we can't use <code>const</code> in order to define the array's memory object.<syntaxhighlight lang="javascript" class="code-continue">
let numbers = [1, 2, 3, 4, 5, 6];
let numbers = [1, 2, 3, 4, 5, 6];
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
numbers = [];
numbers = [];
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
console.log(numbers);
console.log(numbers);
</syntaxhighlight><syntaxhighlight lang="shell-session" class="mlw-continue">
</syntaxhighlight><syntaxhighlight lang="shell-session" class="code-continue">
[]
[]
</syntaxhighlight>
</syntaxhighlight>


Note, the old array exists as an object in the memory and if it is not used anymore, it will be handled by [[JavaScript Basics#Garbage Collector|the garbage collector]]. But if we have its reference we sill able to see and use it.
Note, the old array exists as an object in the memory and if it is not used anymore, it will be handled by [[JavaScript Basics#Garbage Collector|the garbage collector]]. But if we have its reference we sill able to see and use it.
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
let numbers = [1, 2, 3, 4, 5, 6];
let numbers = [1, 2, 3, 4, 5, 6];
let another = numbers;
let another = numbers;
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
numbers = [];
numbers = [];
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
console.log(numbers);
console.log(numbers);
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="shell-session" class="mlw-continue">
<syntaxhighlight lang="shell-session" class="code-continue">
[]
[]
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
console.log(another);
console.log(another);
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="shell-session" class="mlw-continue">
<syntaxhighlight lang="shell-session" class="code-continue">
(6) [1, 2, 3, 4, 5, 6]
(6) [1, 2, 3, 4, 5, 6]
</syntaxhighlight>So the above solution works if do not have references to the original array. Otherwise if you do have multiple references to the original array an you want to change (empty) this array you have to use a different solution.
</syntaxhighlight>So the above solution works if do not have references to the original array. Otherwise if you do have multiple references to the original array an you want to change (empty) this array you have to use a different solution.


'''2.''' Change the array <code>.length</code> property to <code>0</code>. In this case we can use <code>const</code> in order to define the array memory object. This is the best solution!
'''2.''' Change the array <code>.length</code> property to <code>0</code>. In this case we can use <code>const</code> in order to define the array memory object. This is the best solution!
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
const numbers = [1, 2, 3, 4, 5, 6];
const numbers = [1, 2, 3, 4, 5, 6];
const another = numbers;
const another = numbers;
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
numbers.length = 0;
numbers.length = 0;
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
console.log(numbers, another);
console.log(numbers, another);
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="shell-session" class="mlw-continue">
<syntaxhighlight lang="shell-session" class="code-continue">
[] []
[] []
</syntaxhighlight>
</syntaxhighlight>


'''3.''' Use the <code>[https://www.w3schools.com/jsref/jsref_splice.asp .splice()]</code> method.  In this case we can use <code>const</code> in order to define the array memory object.<syntaxhighlight lang="javascript" class="mlw-continue">
'''3.''' Use the <code>[https://www.w3schools.com/jsref/jsref_splice.asp .splice()]</code> method.  In this case we can use <code>const</code> in order to define the array memory object.<syntaxhighlight lang="javascript" class="code-continue">
const numbers = [1, 2, 3, 4, 5, 6];
const numbers = [1, 2, 3, 4, 5, 6];
const another = numbers;
const another = numbers;
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
numbers.splice(0, numbers.length);
numbers.splice(0, numbers.length);
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
console.log(numbers, another);
console.log(numbers, another);
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="shell-session" class="mlw-continue">
<syntaxhighlight lang="shell-session" class="code-continue">
[] []
[] []
</syntaxhighlight>
</syntaxhighlight>


'''4.''' Use the <code>[https://www.w3schools.com/jsref/jsref_pop.asp .pop()]</code> method and a loop.  In this case we can use <code>const</code> in order to define the array memory object. This is not recommended, performance cost solution.
'''4.''' Use the <code>[https://www.w3schools.com/jsref/jsref_pop.asp .pop()]</code> method and a loop.  In this case we can use <code>const</code> in order to define the array memory object. This is not recommended, performance cost solution.
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
const numbers = [1, 2, 3, 4, 5, 6];
const numbers = [1, 2, 3, 4, 5, 6];
const another = numbers;
const another = numbers;
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
while (numbers.length > 0) numbers.pop();
while (numbers.length > 0) numbers.pop();
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
console.log(numbers, another);
console.log(numbers, another);
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="shell-session" class="mlw-continue">
<syntaxhighlight lang="shell-session" class="code-continue">
[] []
[] []
</syntaxhighlight>
</syntaxhighlight>
Line 322: Line 322:
== Combining and Slicing Arrays ==
== Combining and Slicing Arrays ==
=== Combining Arrays ===
=== Combining Arrays ===
To combine these Arrays we can use the <code>[https://www.w3schools.com/jsref/jsref_concat_array.asp .concat(array)]</code> method.<syntaxhighlight lang="javascript" class="mlw-continue">
To combine these Arrays we can use the <code>[https://www.w3schools.com/jsref/jsref_concat_array.asp .concat(array)]</code> method.<syntaxhighlight lang="javascript" class="code-continue">
const first = [1, 2, 3];
const first = [1, 2, 3];
const second = [4, 5, 6];
const second = [4, 5, 6];
</syntaxhighlight><syntaxhighlight lang="javascript" class="mlw-continue">
</syntaxhighlight><syntaxhighlight lang="javascript" class="code-continue">
const combined = first.concat(second);
const combined = first.concat(second);
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
console.log(combined);
console.log(combined);
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="shell-session" class="mlw-continue">
<syntaxhighlight lang="shell-session" class="code-continue">
(6) [1, 2, 3, 4, 5, 6]
(6) [1, 2, 3, 4, 5, 6]
</syntaxhighlight>
</syntaxhighlight>


=== Slicing an Array ===
=== Slicing an Array ===
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
const combined = [1, 2, 3, 4, 5, 6];
const combined = [1, 2, 3, 4, 5, 6];
</syntaxhighlight>In order do slice an Array we can use the <code>[https://www.w3schools.com/jsref/jsref_slice_array.asp .slice(start index, end index)]</code> method.<syntaxhighlight lang="javascript" class="mlw-continue">
</syntaxhighlight>In order do slice an Array we can use the <code>[https://www.w3schools.com/jsref/jsref_slice_array.asp .slice(start index, end index)]</code> method.<syntaxhighlight lang="javascript" class="code-continue">
const slice1 = combined.slice(2, 4);
const slice1 = combined.slice(2, 4);
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
console.log(slice1);
console.log(slice1);
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="shell-session" class="mlw-continue">
<syntaxhighlight lang="shell-session" class="code-continue">
(2) [3, 4]
(2) [3, 4]
</syntaxhighlight>
</syntaxhighlight>


We can use also only the <code>start index</code>.<syntaxhighlight lang="javascript" class="mlw-continue">
We can use also only the <code>start index</code>.<syntaxhighlight lang="javascript" class="code-continue">
const slice2 = combined.slice(3);
const slice2 = combined.slice(3);
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
console.log(slice2);
console.log(slice2);
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="shell-session" class="mlw-continue">
<syntaxhighlight lang="shell-session" class="code-continue">
(3) [4, 5, 6]
(3) [4, 5, 6]
</syntaxhighlight>If we omit also the start index we can create a copy of the array by this method.<syntaxhighlight lang="javascript" class="mlw-continue">
</syntaxhighlight>If we omit also the start index we can create a copy of the array by this method.<syntaxhighlight lang="javascript" class="code-continue">
const copy = combined.slice();
const copy = combined.slice();
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
console.log(copy);
console.log(copy);
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="shell-session" class="mlw-continue">
<syntaxhighlight lang="shell-session" class="code-continue">
(6) [1, 2, 3, 4, 5, 6]
(6) [1, 2, 3, 4, 5, 6]
</syntaxhighlight>
</syntaxhighlight>


=== Reference types ===
=== Reference types ===
The above methods - <code>.slice()</code> and <code>.concat()</code> - are dealing with Primitive types. If we have Reference types in an Array these methods will not copy the referred objects, but only the references to them.<syntaxhighlight lang="javascript" class="mlw-continue">
The above methods - <code>.slice()</code> and <code>.concat()</code> - are dealing with Primitive types. If we have Reference types in an Array these methods will not copy the referred objects, but only the references to them.<syntaxhighlight lang="javascript" class="code-continue">
const first = [{id: 1}, {id: 2}];
const first = [{id: 1}, {id: 2}];
const second = [4, 5, 6];
const second = [4, 5, 6];
const combined = first.concat(second);
const combined = first.concat(second);


</syntaxhighlight><syntaxhighlight lang="javascript" class="mlw-continue">
</syntaxhighlight><syntaxhighlight lang="javascript" class="code-continue">
first[0].id = 888;
first[0].id = 888;
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
console.log(combined);
console.log(combined);
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="shell-session" class="mlw-continue">
<syntaxhighlight lang="shell-session" class="code-continue">
(5) [{id: 888}, {id: 2}, 4, 5, 6]
(5) [{id: 888}, {id: 2}, 4, 5, 6]
</syntaxhighlight>
</syntaxhighlight>


== The Spread Operator ==
== The Spread Operator ==
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
const first = [1, 2, 3];
const first = [1, 2, 3];
const second = [4, 5, 6];
const second = [4, 5, 6];
</syntaxhighlight>In ES6 we can use the ''Spread'' operator - <code class="noTypo">[https://www.w3schools.com/react/react_es6_spread.asp ...spread]</code> - to achieve the same result as the <code>.concat()</code> method from the above section. The ''Spread'' operator approach is cleaner and more flexible.<syntaxhighlight lang="javascript" class="mlw-continue">
</syntaxhighlight>In ES6 we can use the ''Spread'' operator - <code class="noTypo">[https://www.w3schools.com/react/react_es6_spread.asp ...spread]</code> - to achieve the same result as the <code>.concat()</code> method from the above section. The ''Spread'' operator approach is cleaner and more flexible.<syntaxhighlight lang="javascript" class="code-continue">
const combined1 = [...first, ...second];
const combined1 = [...first, ...second];
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
console.log(combined1);
console.log(combined1);
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="shell-session" class="mlw-continue">
<syntaxhighlight lang="shell-session" class="code-continue">
(6) [1, 2, 3, 4, 5, 6]
(6) [1, 2, 3, 4, 5, 6]
</syntaxhighlight>By using the ''Spread'' method we can add elements in a way as it is shown below.<syntaxhighlight lang="javascript" class="mlw-continue">
</syntaxhighlight>By using the ''Spread'' method we can add elements in a way as it is shown below.<syntaxhighlight lang="javascript" class="code-continue">
const combined2 = ['at the beginning', ...first, 'in the middle', ...second, 'at the end'];
const combined2 = ['at the beginning', ...first, 'in the middle', ...second, 'at the end'];
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
console.log(combined2);
console.log(combined2);
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="shell-session" class="mlw-continue">
<syntaxhighlight lang="shell-session" class="code-continue">
(9) ['at the beginning', 1, 2, 3, 'in the middle', 4, 5, 6, 'at the end']
(9) ['at the beginning', 1, 2, 3, 'in the middle', 4, 5, 6, 'at the end']
</syntaxhighlight>We can use the ''Spread'' operator also in order to copy an array.<syntaxhighlight lang="javascript" class="mlw-continue">
</syntaxhighlight>We can use the ''Spread'' operator also in order to copy an array.<syntaxhighlight lang="javascript" class="code-continue">
const copyOfFirst = [...first];
const copyOfFirst = [...first];
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
console.log(copyOfFirst);
console.log(copyOfFirst);
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="shell-session" class="mlw-continue">
<syntaxhighlight lang="shell-session" class="code-continue">
(3) [1, 2, 3]
(3) [1, 2, 3]
</syntaxhighlight>The spread operator also dealing only with Promotive types and just copies the references of Reference types.
</syntaxhighlight>The spread operator also dealing only with Promotive types and just copies the references of Reference types.


== Iterating an Array ==
== Iterating an Array ==
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
const numbers = [1, 2, 3];
const numbers = [1, 2, 3];
</syntaxhighlight>
</syntaxhighlight>
Use <code>[https://www.w3schools.com/js/js_loop_forof.asp for.. of..]</code> loop.
Use <code>[https://www.w3schools.com/js/js_loop_forof.asp for.. of..]</code> loop.
{{collapse|
{{collapse|
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
for (let number in numbers) console.log(number);
for (let number in numbers) console.log(number);
</syntaxhighlight>
</syntaxhighlight>
Line 431: Line 431:
Use <code>[https://www.w3schools.com/jsref/jsref_foreach.asp .forEach(calback_f)]</code> method.
Use <code>[https://www.w3schools.com/jsref/jsref_foreach.asp .forEach(calback_f)]</code> method.
{{collapse|
{{collapse|
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
numbers.forEach(function(number) { console.log(number) });
numbers.forEach(function(number) { console.log(number) });
</syntaxhighlight>
</syntaxhighlight>
Line 443: Line 443:


{{collapse|
{{collapse|
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
numbers.forEach(number => console.log(number));
numbers.forEach(number => console.log(number));
</syntaxhighlight>
</syntaxhighlight>
Line 453: Line 453:
</syntaxhighlight>
</syntaxhighlight>
|l=#Output}}The loopback function can have second parameter, which is <code>index</code>.
|l=#Output}}The loopback function can have second parameter, which is <code>index</code>.
{{collapse|<syntaxhighlight lang="javascript" class="mlw-continue">
{{collapse|<syntaxhighlight lang="javascript" class="code-continue">
numbers.forEach((element, index) => console.log(index, element));
numbers.forEach((element, index) => console.log(index, element));
</syntaxhighlight>|<syntaxhighlight lang="shell-session" class="mlw-collapsed-output">
</syntaxhighlight>|<syntaxhighlight lang="shell-session" class="mlw-collapsed-output">
Line 466: Line 466:
== Joining an Array and Splitting a String ==
== Joining an Array and Splitting a String ==
The <code class="noTypo">[https://www.w3schools.com/jsref/jsref_join.asp .join('optional field separator')]</code> method could be used to convert an Array into string.
The <code class="noTypo">[https://www.w3schools.com/jsref/jsref_join.asp .join('optional field separator')]</code> method could be used to convert an Array into string.
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
const numbers = [1, 2, 3, 4, 5, 6];
const numbers = [1, 2, 3, 4, 5, 6];
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
const joined = numbers.join('-');
const joined = numbers.join('-');
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
console.log(joined);
console.log(joined);
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="shell-session" class="mlw-continue">
<syntaxhighlight lang="shell-session" class="code-continue">
1-2-3-4-5-6
1-2-3-4-5-6
</syntaxhighlight>
</syntaxhighlight>
We can use the <code class="noTypo">[https://www.w3schools.com/jsref/jsref_split.asp .split('field separator')]</code> method (that belongs to the String objects) in order to convert a String to an Array.
We can use the <code class="noTypo">[https://www.w3schools.com/jsref/jsref_split.asp .split('field separator')]</code> method (that belongs to the String objects) in order to convert a String to an Array.
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
const text = 'This is the message';
const text = 'This is the message';
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
const array = text.split(' ');
const array = text.split(' ');
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
console.log(array);
console.log(array);
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="shell-session" class="mlw-continue">
<syntaxhighlight lang="shell-session" class="code-continue">
(4) ['This', 'is', 'the', 'message']
(4) ['This', 'is', 'the', 'message']
</syntaxhighlight>
</syntaxhighlight>
Line 495: Line 495:


=== Primitive types ===
=== Primitive types ===
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
const numbers = [2, 3, 1];
const numbers = [2, 3, 1];
</syntaxhighlight>Use <code>[https://www.w3schools.com/jsref/jsref_sort.asp .sort()]</code> method. It sorts the elements of an array, overwrites the original array, sorts the elements as strings in alphabetical and ascending order.<syntaxhighlight lang="javascript" class="mlw-continue">
</syntaxhighlight>Use <code>[https://www.w3schools.com/jsref/jsref_sort.asp .sort()]</code> method. It sorts the elements of an array, overwrites the original array, sorts the elements as strings in alphabetical and ascending order.<syntaxhighlight lang="javascript" class="code-continue">
numbers.sort();
numbers.sort();
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
console.log(numbers);
console.log(numbers);
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="shell-session" class="mlw-continue">
<syntaxhighlight lang="shell-session" class="code-continue">
(3) [1, 2, 3]
(3) [1, 2, 3]
</syntaxhighlight>Use <code>[https://www.w3schools.com/jsref/jsref_reverse.asp .reverse()]</code> method. The array after it has been reversed.<syntaxhighlight lang="javascript" class="mlw-continue">
</syntaxhighlight>Use <code>[https://www.w3schools.com/jsref/jsref_reverse.asp .reverse()]</code> method. The array after it has been reversed.<syntaxhighlight lang="javascript" class="code-continue">
numbers.reverse();
numbers.reverse();
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
console.log(numbers);
console.log(numbers);
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="shell-session" class="mlw-continue">
<syntaxhighlight lang="shell-session" class="code-continue">
(3) [3, 2, 1]
(3) [3, 2, 1]
</syntaxhighlight>
</syntaxhighlight>


=== Reference types ===
=== Reference types ===
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
const numbers = [
const numbers = [
     {id: 1, name: 'Node.js'},  // When sorting by name this should be Third
     {id: 1, name: 'Node.js'},  // When sorting by name this should be Third
Line 522: Line 522:
     {id: 2, name: 'JavaScript'} // When sorting by name this should be Second
     {id: 2, name: 'JavaScript'} // When sorting by name this should be Second
];
];
</syntaxhighlight>Use <code>[https://www.w3schools.com/jsref/jsref_sort.asp .sort(callback_fn)]</code> method. There the sorting will be dove via ASCII order, reference: https://www.asciitable.com/<syntaxhighlight lang="javascript" class="mlw-continue">
</syntaxhighlight>Use <code>[https://www.w3schools.com/jsref/jsref_sort.asp .sort(callback_fn)]</code> method. There the sorting will be dove via ASCII order, reference: https://www.asciitable.com/<syntaxhighlight lang="javascript" class="code-continue">
numbers.sort(function(a, b) {
numbers.sort(function(a, b) {
     // Remove case sensitivity
     // Remove case sensitivity
Line 533: Line 533:
});
});
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
console.log(numbers);
console.log(numbers);
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="shell-session" class="mlw-continue">
<syntaxhighlight lang="shell-session" class="code-continue">
(3) [{id: 3, name: 'C++'}, {id: 2, name: 'JavaScript'}, {id: 1, name: 'Node.js'}]
(3) [{id: 3, name: 'C++'}, {id: 2, name: 'JavaScript'}, {id: 1, name: 'Node.js'}]
</syntaxhighlight>
</syntaxhighlight>


== Testing the Elements of an Array ==
== Testing the Elements of an Array ==
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
const numbers = [2, 3, 1];
const numbers = [2, 3, 1];
</syntaxhighlight>Use <code>[https://www.w3schools.com/jsref/jsref_every.asp .every(callback_fn)]</code> method. It executes a function for each array element, returns <code>true</code> if the function returns true for all elements, returns <code>false</code> if the function returns false for one element, does not execute the function for empty elements, does not change the original array. Available in ES6+.<syntaxhighlight lang="javascript" class="mlw-continue">
</syntaxhighlight>Use <code>[https://www.w3schools.com/jsref/jsref_every.asp .every(callback_fn)]</code> method. It executes a function for each array element, returns <code>true</code> if the function returns true for all elements, returns <code>false</code> if the function returns false for one element, does not execute the function for empty elements, does not change the original array. Available in ES6+.<syntaxhighlight lang="javascript" class="code-continue">
let areAllPositive = numbers.every(function(value) {
let areAllPositive = numbers.every(function(value) {
     return value >= 0;
     return value >= 0;
});
});
</syntaxhighlight><syntaxhighlight lang="javascript" class="mlw-continue">
</syntaxhighlight><syntaxhighlight lang="javascript" class="code-continue">
console.log(areAllPositive);
console.log(areAllPositive);
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="shell-session" class="mlw-continue">
<syntaxhighlight lang="shell-session" class="code-continue">
true
true
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
numbers[3] = -2;
numbers[3] = -2;
areAllPositive = numbers.every(value => value >= 0);
areAllPositive = numbers.every(value => value >= 0);
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
console.log(areAllPositive);
console.log(areAllPositive);
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="shell-session" class="mlw-continue">
<syntaxhighlight lang="shell-session" class="code-continue">
false
false
</syntaxhighlight>Use <code>[https://www.w3schools.com/jsref/jsref_some.asp .some(callback_fn)]</code> method. It checks if any array elements pass a test (provided as a function); executes the function once for each array element: 1) If the function returns true, some() returns true and stops, 2) If the function returns false, some() returns false and stops; does not execute the function for empty array elements; does not change the original array.<syntaxhighlight lang="javascript" class="mlw-continue">
</syntaxhighlight>Use <code>[https://www.w3schools.com/jsref/jsref_some.asp .some(callback_fn)]</code> method. It checks if any array elements pass a test (provided as a function); executes the function once for each array element: 1) If the function returns true, some() returns true and stops, 2) If the function returns false, some() returns false and stops; does not execute the function for empty array elements; does not change the original array.<syntaxhighlight lang="javascript" class="code-continue">
let atLeastOneNegative = numbers.some(function(value) {
let atLeastOneNegative = numbers.some(function(value) {
     return value < 0;
     return value < 0;
});
});
</syntaxhighlight><syntaxhighlight lang="javascript" class="mlw-continue">
</syntaxhighlight><syntaxhighlight lang="javascript" class="code-continue">
console.log(atLeastOnePositive);
console.log(atLeastOnePositive);
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="shell-session" class="mlw-continue">
<syntaxhighlight lang="shell-session" class="code-continue">
true
true
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
numbers.pop();
numbers.pop();
atLeastOneNegative = numbers.some(value => value < 0);
atLeastOneNegative = numbers.some(value => value < 0);
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
console.log(atLeastOneNegative);
console.log(atLeastOneNegative);
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="shell-session" class="mlw-continue">
<syntaxhighlight lang="shell-session" class="code-continue">
false
false
</syntaxhighlight>
</syntaxhighlight>


== Filtering an Array ==
== Filtering an Array ==
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
const numbers = [2, -1, 3, -7, 1, 5];
const numbers = [2, -1, 3, -7, 1, 5];
</syntaxhighlight>Use <code>[https://www.w3schools.com/jsref/jsref_filter.asp .filter(callback_fn)]</code> in order to filter an array based on a search criteria. It creates a new array filled with elements that pass a test provided by a function, does not execute the function for empty elements, does not change the original array.
</syntaxhighlight>Use <code>[https://www.w3schools.com/jsref/jsref_filter.asp .filter(callback_fn)]</code> in order to filter an array based on a search criteria. It creates a new array filled with elements that pass a test provided by a function, does not execute the function for empty elements, does not change the original array.


In the next example we will filter only the positive values. And in addition will sort them in a reverse order.<syntaxhighlight lang="javascript" class="mlw-continue">
In the next example we will filter only the positive values. And in addition will sort them in a reverse order.<syntaxhighlight lang="javascript" class="code-continue">
let onlyPositive = numbers.filter(function(value) {
let onlyPositive = numbers.filter(function(value) {
     return value >= 0;
     return value >= 0;
Line 595: Line 595:


* ''Better practice is to put chaining methods on a new line.''
* ''Better practice is to put chaining methods on a new line.''
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
console.log(onlyPositive);
console.log(onlyPositive);
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="shell-session" class="mlw-continue">
<syntaxhighlight lang="shell-session" class="code-continue">
(4) [5, 3, 2, 1]
(4) [5, 3, 2, 1]
</syntaxhighlight>
</syntaxhighlight>


== Mapping an Array ==
== Mapping an Array ==
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
const items = ['item 1', 'item 2', 'item 3'];
const items = ['item 1', 'item 2', 'item 3'];
</syntaxhighlight>With the <code>[https://www.w3schools.com/jsref/jsref_map.asp .map(callback_fn)]</code> method we can map each element in an Array to something else. It creates a new array from calling a function for every array element, calls a function once for each element in an array, does not execute the function for empty elements, does not change the original array.<syntaxhighlight lang="javascript" class="mlw-continue">
</syntaxhighlight>With the <code>[https://www.w3schools.com/jsref/jsref_map.asp .map(callback_fn)]</code> method we can map each element in an Array to something else. It creates a new array from calling a function for every array element, calls a function once for each element in an array, does not execute the function for empty elements, does not change the original array.<syntaxhighlight lang="javascript" class="code-continue">
const itemsList = '<ul>' + items.map(item => '<li>' + item + '</li>').join('') + '</ul>';  // Note ',' is the default joining separator of .join()
const itemsList = '<ul>' + items.map(item => '<li>' + item + '</li>').join('') + '</ul>';  // Note ',' is the default joining separator of .join()
</syntaxhighlight><syntaxhighlight lang="javascript" class="mlw-continue">
</syntaxhighlight><syntaxhighlight lang="javascript" class="code-continue">
console.log(itemsList);
console.log(itemsList);
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="html" class="mlw-continue">
<syntaxhighlight lang="html" class="code-continue">
<ul><li>item 1</li><li>item 2</li><li>item 3</li></ul>
<ul><li>item 1</li><li>item 2</li><li>item 3</li></ul>
</syntaxhighlight>
</syntaxhighlight>


== Convert an Array of Primitives into an Array of References ==
== Convert an Array of Primitives into an Array of References ==
This approach should be available with all kind of (callback) functions - here we will use the <code>.map()</code> method.<syntaxhighlight lang="javascript" class="mlw-continue">
This approach should be available with all kind of (callback) functions - here we will use the <code>.map()</code> method.<syntaxhighlight lang="javascript" class="code-continue">
const numbers = [1, 2, 3];
const numbers = [1, 2, 3];
</syntaxhighlight>Using a Standard function and explicit syntax.<syntaxhighlight lang="javascript" class="mlw-continue">
</syntaxhighlight>Using a Standard function and explicit syntax.<syntaxhighlight lang="javascript" class="code-continue">
const items = numbers.map(function(n) {
const items = numbers.map(function(n) {
     const obj = {'value': n};
     const obj = {'value': n};
     return obj;
     return obj;
});
});
</syntaxhighlight>Using a Standard function and short syntax.<syntaxhighlight lang="javascript" class="mlw-continue">
</syntaxhighlight>Using a Standard function and short syntax.<syntaxhighlight lang="javascript" class="code-continue">
const items = numbers.map(function(n) {
const items = numbers.map(function(n) {
     return {'value': n};
     return {'value': n};
});
});
</syntaxhighlight>Using an Arrow function. Note in this case we need to enclose the output object in parenthesis, because in otherwise the JavaScript engine will threat the curly braces as code block.<syntaxhighlight lang="javascript" class="mlw-continue">
</syntaxhighlight>Using an Arrow function. Note in this case we need to enclose the output object in parenthesis, because in otherwise the JavaScript engine will threat the curly braces as code block.<syntaxhighlight lang="javascript" class="code-continue">
const items = numbers.map(n => ({'value': n}) );
const items = numbers.map(n => ({'value': n}) );
</syntaxhighlight>The output of the three examples is the same.<syntaxhighlight lang="javascript" class="mlw-continue">
</syntaxhighlight>The output of the three examples is the same.<syntaxhighlight lang="javascript" class="code-continue">
console.log(items);
console.log(items);
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="shell-session" class="mlw-continue">
<syntaxhighlight lang="shell-session" class="code-continue">
(3) [{value: '1'}, {value: '2'}, {value: '3'}]
(3) [{value: '1'}, {value: '2'}, {value: '3'}]
</syntaxhighlight>
</syntaxhighlight>


== Reducing an Array ==
== Reducing an Array ==
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
const numbers = [1, -1, 2, 3];
const numbers = [1, -1, 2, 3];
</syntaxhighlight>Using [https://www.w3schools.com/js/js_loop_forof.asp <code>for.. of..</code>] loop - the old way.<syntaxhighlight lang="javascript" class="mlw-continue">
</syntaxhighlight>Using [https://www.w3schools.com/js/js_loop_forof.asp <code>for.. of..</code>] loop - the old way.<syntaxhighlight lang="javascript" class="code-continue">
let sum = 0;
let sum = 0;
for (let n of numbers) sum += n;
for (let n of numbers) sum += n;
      
      
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
console.log(sum);
console.log(sum);
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="shell-session" class="mlw-continue">
<syntaxhighlight lang="shell-session" class="code-continue">
5
5
</syntaxhighlight>
</syntaxhighlight>
Using <code>[https://www.w3schools.com/jsref/jsref_reduce.asp .reduce(function(total, currentValue, currentIndex, arr), initialValue)]</code> method of the array objects. It executes a reducer function for array element, returns a single value: the function's accumulated result, does not execute the function for empty array elements, does not change the original array.
Using <code>[https://www.w3schools.com/jsref/jsref_reduce.asp .reduce(function(total, currentValue, currentIndex, arr), initialValue)]</code> method of the array objects. It executes a reducer function for array element, returns a single value: the function's accumulated result, does not execute the function for empty array elements, does not change the original array.
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
let sum = numbers.reduce(function(accumulator, currentValue) {
let sum = numbers.reduce(function(accumulator, currentValue) {
     return accumulator + currentValue;
     return accumulator + currentValue;
Line 656: Line 656:
      
      
</syntaxhighlight>
</syntaxhighlight>
Or as Arrow function and without <code>initalValue</code> for the <code>total</code>.<syntaxhighlight lang="javascript" class="mlw-continue">
Or as Arrow function and without <code>initalValue</code> for the <code>total</code>.<syntaxhighlight lang="javascript" class="code-continue">
let sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue);
let sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue);
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
console.log(sum);
console.log(sum);
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="shell-session" class="mlw-continue">
<syntaxhighlight lang="shell-session" class="code-continue">
5
5
</syntaxhighlight>
</syntaxhighlight>

Latest revision as of 08:28, 26 September 2022

Ref­er­ences

See al­so:

De­clar­ing an Ar­ray

const numbers = [3, 4];  // Array Literal
typeof numbers;          // "object"

Con­stant does not stop us from mod­i­fy­ing the con­tent of an Ar­ray, we can adding and re­move el­e­ments. Just we can't re­as­sign the vari­able to dif­fer­ent type.

In JavaScript, the Ar­rays are kind of ob­jects, so the are a cou­ple of built-in prop­er­ties [like .length] and meth­ods [like .in­dex­Of()].

Re­mem­ber the in­dex of the Ar­rays starts from 0.

[1, 2, 3, 1, 4]
 0  1  2  3  4

Adding El­e­ments to an Ar­ray

Add el­e­ments to the end of an Ar­ray by us­ing .push(elements) method. It adds new items to the end of an ar­ray, changes the length of the ar­ray, re­turns the new length.

numbers.push(5, 6);
console.log(numbers);
(4) [3, 4, 5, 6]

Add el­e­ments to the be­gin­ning of an Ar­ray by us­ing .unshift(elements) method. It adds new el­e­ments to the be­gin­ning of an ar­ray, over­writes the orig­i­nal ar­ray.

numbers.unshift(1, 2);
console.log(numbers);
(6) [1, 2, 3, 4, 5, 6]

Add el­e­ments to the mid­dle of an Ar­ray by us­ing .splice(index, delete count, el­e­ments to add) method. It adds and/​​​or re­moves ar­ray el­e­ments, over­writes the orig­i­nal ar­ray.

numbers.splice(2, 0, 'a', 'b'); // 0 means we won't remove elements
console.log(numbers);
(8) [1, 2, 'a', 'b', 3, 4, 5, 6]

Find­ing El­e­ments in an Ar­ray

Find­ing Prim­i­tive types in an Ar­ray

const numbers = [1, 2, 3, 1, 4];

By us­ing .indexOf(element, start_index=0) method we can find the first oc­cur­rence of an el­e­ment.

console.log(numbers.indexOf(1));
0
console.log(numbers.indexOf(3));
2
console.log(numbers.indexOf('c')); // This element doesn't exist
-1

By us­ing .lastIndexOf(element, start_index=array_lenght) method we can find the last oc­cur­rence of an el­e­ment.

console.log(numbers.latIndexOf(1));
3

Test whether a giv­en (prim­i­tive) el­e­ment ex­ists in an Ar­ray

const numbers = [1, 2, 3, 1, 4];

The old way, by us­ing .indexOf(element, start_index=0) method.

console.log(numbers.indexOf(1) !== -1); // will return 'true' if one or more elements with value 1 exist in the array 'numbers'
if (numbers.indexOf(1) !== -1) { ... }

The mod­ern way, by us­ing .includes(element, start_index=0) method.

console.log(numbers.includes(1)); // will return 'true' if one or more elements with value 1 exist in the array 'numbers'
if (numbers.includes(1)) { ... }

Start In­dex

All these meth­ods ah a sec­ond op­tion­al pa­ra­me­ter which is start in­dex.

const numbers = [1, 2, 3, 1, 4, 1, 5, 6];
console.log(numbers.length);
8
console.log(numbers.indexOf(1)); // start index = 0
0
console.log(numbers.indexOf(1, 2)); // start index = 2
3
console.log(numbers.lastIndexOf(1)); // start index = array_length, and backwods count
5
console.log(numbers.lastIndexOf(1, 4)); // start index = 4, and backwods count
3

Find­ing Ref­er­ence types in an Ar­ray

const courses = [
    {id: 1, name: 'a'},
    {id: 2, name: 'b'}
];

By us­ing .find(callback_fn) method we can find an Ob­ject with­in Ar­ray, which has a giv­en prop­er­ty.

let course_A_exist = courses.find(function(course) {
   return course.name === 'a'; 
});
console.log(course_A_exist);  // will return 'undefined' if the element dosn't exist
{id: 1, name: 'a'}

By us­ing .findIndex(callback_fn) method we can find the In­dex of an Ob­ject with­in Ar­ray, which has a giv­en prop­er­ty.

let course_B_index = courses.findIndex(function(course) {
   return course.name === 'b'; 
});
console.log(course_B_index);  // will return '-1' if the element dosn't exist
1

Ar­row Func­tions

Here is how to trans­form the above call­back func­tion to an Ar­row func­tion.

The ini­tial state of the call­back func­tion.

#Init state
let course_A_exist = courses.find(function(course) {
   return course.name === 'a'; 
});

Step 1, re­move the func­tion key­word, and sep­a­rate the pa­ra­me­ters of the func­tion from its body put a fat ar­row.

#Step 1
let course_A_exist = courses.find((course) => {
   return course.name === 'a'; 
});

Step 2, if the func­tion have a sin­gle pa­ra­me­ter we can al­so re­move the paren­the­ses.

#Step 2
let course_A_exist = courses.find(course => {
   return course.name === 'a'; 
});

If you do not have any pa­ra­me­ters you have to pass emp­ty paren­the­ses:

let course_A_exist = courses.find(() => { ... });

Step 3, if the func­tion is a sin­gle line of code, we can make this code even short­er: 1) get rid of the re­turn key­word, 2) re­move the curly braces, 3) place every­thing on one line.

#Rslt
let course_A_exist = courses.find(course => course.name === 'a');

Re­mov­ing El­e­ments of an Ar­ray

const numbers = [1, 2, 3, 4, 5, 6];

Re­move el­e­ments to the end of an Ar­ray by us­ing .pop(elements) method. It re­moves (pops) the last el­e­ment of an ar­ray, changes the orig­i­nal ar­ray, re­turns the re­moved el­e­ment.

let last = numbers.pop();
console.log(numbers);
(5) [1, 2, 3, 4, 5]
console.log(last);
6

Re­move el­e­ments to the be­gin­ning of an Ar­ray by us­ing .shift(elements) method. It re­moves the first item of an ar­ray, changes the orig­i­nal ar­ray, re­turns the shift­ed el­e­ment.

let first = numbers.shift();
console.log(numbers);
(4) [2, 3, 4, 5]
console.log(first);
1

Re­move el­e­ments to the mid­dle of an Ar­ray by us­ing .splice(index, delete count, el­e­ments to add) method. It adds and/​​​or re­moves ar­ray el­e­ments, over­writes the orig­i­nal ar­ray.

numbers.splice(1, 2); // we will remove 2 elemets starting from index 1
console.log(numbers);
(2) [2, 5]

Emp­ty­ing an Ar­ray

1. Re­as­sign to a new emp­ty ar­ray. In this case we can't use con­st in or­der to de­fine the array's mem­o­ry ob­ject.

let numbers = [1, 2, 3, 4, 5, 6];
numbers = [];
console.log(numbers);
[]

Note, the old ar­ray ex­ists as an ob­ject in the mem­o­ry and if it is not used any­more, it will be han­dled by the garbage col­lec­tor. But if we have its ref­er­ence we sill able to see and use it.

let numbers = [1, 2, 3, 4, 5, 6];
let another = numbers;
numbers = [];
console.log(numbers);
[]
console.log(another);
(6) [1, 2, 3, 4, 5, 6]

So the above so­lu­tion works if do not have ref­er­ences to the orig­i­nal ar­ray. Oth­er­wise if you do have mul­ti­ple ref­er­ences to the orig­i­nal ar­ray an you want to change (emp­ty) this ar­ray you have to use a dif­fer­ent so­lu­tion.

2. Change the ar­ray .length prop­er­ty to 0. In this case we can use con­st in or­der to de­fine the ar­ray mem­o­ry ob­ject. This is the best so­lu­tion!

const numbers = [1, 2, 3, 4, 5, 6];
const another = numbers;
numbers.length = 0;
console.log(numbers, another);
[] []

3. Use the .splice() method. In this case we can use con­st in or­der to de­fine the ar­ray mem­o­ry ob­ject.

const numbers = [1, 2, 3, 4, 5, 6];
const another = numbers;
numbers.splice(0, numbers.length);
console.log(numbers, another);
[] []

4. Use the .pop() method and a loop. In this case we can use con­st in or­der to de­fine the ar­ray mem­o­ry ob­ject. This is not rec­om­mend­ed, per­for­mance cost so­lu­tion.

const numbers = [1, 2, 3, 4, 5, 6];
const another = numbers;
while (numbers.length > 0) numbers.pop();
console.log(numbers, another);
[] []

Com­bin­ing and Slic­ing Ar­rays

Com­bin­ing Ar­rays

To com­bine these Ar­rays we can use the .concat(array) method.

const first = [1, 2, 3];
const second = [4, 5, 6];
const combined = first.concat(second);
console.log(combined);
(6) [1, 2, 3, 4, 5, 6]

Slic­ing an Ar­ray

const combined = [1, 2, 3, 4, 5, 6];

In or­der do slice an Ar­ray we can use the .slice(start in­dex, end in­dex) method.

const slice1 = combined.slice(2, 4);
console.log(slice1);
(2) [3, 4]

We can use al­so on­ly the start in­dex.

const slice2 = combined.slice(3);
console.log(slice2);
(3) [4, 5, 6]

If we omit al­so the start in­dex we can cre­ate a copy of the ar­ray by this method.

const copy = combined.slice();
console.log(copy);
(6) [1, 2, 3, 4, 5, 6]

Ref­er­ence types

The above meth­ods – .slice() and .con­cat() – are deal­ing with Prim­i­tive types. If we have Ref­er­ence types in an Ar­ray these meth­ods will not copy the re­ferred ob­jects, but on­ly the ref­er­ences to them.

const first = [{id: 1}, {id: 2}];
const second = [4, 5, 6];
const combined = first.concat(second);
first[0].id = 888;
console.log(combined);
(5) [{id: 888}, {id: 2}, 4, 5, 6]

The Spread Op­er­a­tor

const first = [1, 2, 3];
const second = [4, 5, 6];

In ES6 we can use the Spread op­er­a­tor – ...spread – to achieve the same re­sult as the .con­cat() method from the above sec­tion. The Spread op­er­a­tor ap­proach is clean­er and more flex­i­ble.

const combined1 = [...first, ...second];
console.log(combined1);
(6) [1, 2, 3, 4, 5, 6]

By us­ing the Spread method we can add el­e­ments in a way as it is shown be­low.

const combined2 = ['at the beginning', ...first, 'in the middle', ...second, 'at the end'];
console.log(combined2);
(9) ['at the beginning', 1, 2, 3, 'in the middle', 4, 5, 6, 'at the end']

We can use the Spread op­er­a­tor al­so in or­der to copy an ar­ray.

const copyOfFirst = [...first];
console.log(copyOfFirst);
(3) [1, 2, 3]

The spread op­er­a­tor al­so deal­ing on­ly with Pro­mo­tive types and just copies the ref­er­ences of Ref­er­ence types.

It­er­at­ing an Ar­ray

const numbers = [1, 2, 3];

Use for.. of.. loop.

for (let number in numbers) console.log(number);
#Out­put
1
2
3

Use .forEach(calback_f) method.

numbers.forEach(function(number) { console.log(number) });
#Out­put
1
2
3
numbers.forEach(number => console.log(number));
#Out­put
1
2
3

The loop­back func­tion can have sec­ond pa­ra­me­ter, which is in­dex.

numbers.forEach((element, index) => console.log(index, element));
#Out­put
0 1
1 2
2 3

Join­ing an Ar­ray and Split­ting a String

The .join('optional field separator') method could be used to con­vert an Ar­ray in­to string.

const numbers = [1, 2, 3, 4, 5, 6];
const joined = numbers.join('-');
console.log(joined);
1-2-3-4-5-6

We can use the .split('field separator') method (that be­longs to the String ob­jects) in or­der to con­vert a String to an Ar­ray.

const text = 'This is the message';
const array = text.split(' ');
console.log(array);
(4) ['This', 'is', 'the', 'message']

Sort­ing and Re­verse Ar­rays

Prim­i­tive types

const numbers = [2, 3, 1];

Use .sort() method. It sorts the el­e­ments of an ar­ray, over­writes the orig­i­nal ar­ray, sorts the el­e­ments as strings in al­pha­bet­i­cal and as­cend­ing or­der.

numbers.sort();
console.log(numbers);
(3) [1, 2, 3]

Use .re­verse() method. The ar­ray af­ter it has been re­versed.

numbers.reverse();
console.log(numbers);
(3) [3, 2, 1]

Ref­er­ence types

const numbers = [
    {id: 1, name: 'Node.js'},   // When sorting by name this should be Third
    {id: 3, name: 'C++'},       // When sorting by name this should be First
    {id: 2, name: 'JavaScript'} // When sorting by name this should be Second
];

Use .sort(callback_fn) method. There the sort­ing will be dove via ASCII or­der, ref­er­ence: https://​www​.asciitable​.com/

numbers.sort(function(a, b) {
    // Remove case sensitivity
    const nameA = a.name.toLowerCase(); // .toUpperCase() is also valid,
    const nameB = b.name.toLowerCase(); // but both should be equal
    
    if (nameA < nameB) return -1;
    if (nameA > nameB) return 1;
    return 0;
});
console.log(numbers);
(3) [{id: 3, name: 'C++'}, {id: 2, name: 'JavaScript'}, {id: 1, name: 'Node.js'}]

Test­ing the El­e­ments of an Ar­ray

const numbers = [2, 3, 1];

Use .every(callback_fn) method. It ex­e­cutes a func­tion for each ar­ray el­e­ment, re­turns true if the func­tion re­turns true for all el­e­ments, re­turns false if the func­tion re­turns false for one el­e­ment, does not ex­e­cute the func­tion for emp­ty el­e­ments, does not change the orig­i­nal ar­ray. Avail­able in ES6+.

let areAllPositive = numbers.every(function(value) {
    return value >= 0;
});
console.log(areAllPositive);
true
numbers[3] = -2;
areAllPositive = numbers.every(value => value >= 0);
console.log(areAllPositive);
false

Use .some(callback_fn) method. It checks if any ar­ray el­e­ments pass a test (pro­vid­ed as a func­tion); ex­e­cutes the func­tion once for each ar­ray el­e­ment: 1) If the func­tion re­turns true, some() re­turns true and stops, 2) If the func­tion re­turns false, some() re­turns false and stops; does not ex­e­cute the func­tion for emp­ty ar­ray el­e­ments; does not change the orig­i­nal ar­ray.

let atLeastOneNegative = numbers.some(function(value) {
    return value < 0;
});
console.log(atLeastOnePositive);
true
numbers.pop();
atLeastOneNegative = numbers.some(value => value < 0);
console.log(atLeastOneNegative);
false

Fil­ter­ing an Ar­ray

const numbers = [2, -1, 3, -7, 1, 5];

Use .filter(callback_fn) in or­der to fil­ter an ar­ray based on a search cri­te­ria. It cre­ates a new ar­ray filled with el­e­ments that pass a test pro­vid­ed by a func­tion, does not ex­e­cute the func­tion for emp­ty el­e­ments, does not change the orig­i­nal ar­ray. In the next ex­am­ple we will fil­ter on­ly the pos­i­tive val­ues. And in ad­di­tion will sort them in a re­verse or­der.

let onlyPositive = numbers.filter(function(value) {
    return value >= 0;
}).sort().reverse();
  • Bet­ter prac­tice is to put chain­ing meth­ods on a new line.
console.log(onlyPositive);
(4) [5, 3, 2, 1]

Map­ping an Ar­ray

const items = ['item 1', 'item 2', 'item 3'];

With the .map(callback_fn) method we can map each el­e­ment in an Ar­ray to some­thing else. It cre­ates a new ar­ray from call­ing a func­tion for every ar­ray el­e­ment, calls a func­tion once for each el­e­ment in an ar­ray, does not ex­e­cute the func­tion for emp­ty el­e­ments, does not change the orig­i­nal ar­ray.

const itemsList = '<ul>' + items.map(item => '<li>' + item + '</li>').join('') + '</ul>';  // Note ',' is the default joining separator of .join()
console.log(itemsList);
<ul><li>item 1</li><li>item 2</li><li>item 3</li></ul>

Con­vert an Ar­ray of Prim­i­tives in­to an Ar­ray of Ref­er­ences

This ap­proach should be avail­able with all kind of (call­back) func­tions – here we will use the .map() method.

const numbers = [1, 2, 3];

Us­ing a Stan­dard func­tion and ex­plic­it syn­tax.

const items = numbers.map(function(n) {
    const obj = {'value': n};
    return obj;
});

Us­ing a Stan­dard func­tion and short syn­tax.

const items = numbers.map(function(n) {
    return {'value': n};
});

Us­ing an Ar­row func­tion. Note in this case we need to en­close the out­put ob­ject in paren­the­sis, be­cause in oth­er­wise the JavaScript en­gine will threat the curly braces as code block.

const items = numbers.map(n => ({'value': n}) );

The out­put of the three ex­am­ples is the same.

console.log(items);
(3) [{value: '1'}, {value: '2'}, {value: '3'}]

Re­duc­ing an Ar­ray

const numbers = [1, -1, 2, 3];

Us­ing for.. of.. loop – the old way.

let sum = 0;
for (let n of numbers) sum += n;
console.log(sum);
5

Us­ing .reduce(function(total, cur­rent­Val­ue, cur­rentIn­dex, arr), ini­tial­Val­ue) method of the ar­ray ob­jects. It ex­e­cutes a re­duc­er func­tion for ar­ray el­e­ment, re­turns a sin­gle val­ue: the function's ac­cu­mu­lat­ed re­sult, does not ex­e­cute the func­tion for emp­ty ar­ray el­e­ments, does not change the orig­i­nal ar­ray.

let sum = numbers.reduce(function(accumulator, currentValue) {
    return accumulator + currentValue;
}, 0); // accumulator = 0; if we omit this value the 'accumulator' will be initialized with the value of the firs element

Or as Ar­row func­tion and with­out ini­tal­Val­ue for the to­tal.

let sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue);
console.log(sum);
5