Array Tips
+ With an array concats to a string
Using the + sign with an array might give some unpredictable results.
var value = ["a","b"] + ["c","d"]
alert(value);
alert(typeof value);
When you run this script value will be a, bc, d
This is also the case with numbers
var value = [33, 55] + [10, 22];
alert(value);
alert(typeof value);
This will get the following result:
value will be: 33, 5510, 22
And value will have become a string.
Add an element to an array
Here is a simple method to add an element to an array.
array = [1,2,3]
array = [...array, 5]
alert(array)
Here is a simple method to add an element to an array.
array = [1,2,3]
array = [...array, 5]
alert(array)
A different way to adress array elements
array = ["cellar", "Kitchen", "Livingroom", "Mancave"]
alert(array.at(3))
The alert shows "Mancave" kust like it would if you used alert(array[3])
array = ["cellar", "Kitchen", "Livingroom", "Mancave"]
alert(array.at(3))
The alert shows "Mancave" kust like it would if you used alert(array[3])
Add an element to an array at a pre-defined location
This snippet shows how to add an element to an array at a predifined place.
var testarray=['C++','Lua','Python']
testarray.splice(1,0,'Javascript')
alert(testarray)
splice inserts the new language at array index 1. The 0 in the splice command tells how many elements must be removed. In this case we want to remove nothing so the second value in the splice command is 0.
This snippet shows how to add an element to an array at a predifined place.
var testarray=['C++','Lua','Python']
testarray.splice(1,0,'Javascript')
alert(testarray)
splice inserts the new language at array index 1. The 0 in the splice command tells how many elements must be removed. In this case we want to remove nothing so the second value in the splice command is 0.
Add an element to an array only if it is new
The next snippet shows how to add an element to an array but only if it is not already present in the array.
var array = ['test1','test2'];
var element = 'test2';
if(array.indexOf(element) === -1) {
array.push(element);
}
The next snippet shows how to add an element to an array but only if it is not already present in the array.
var array = ['test1','test2'];
var element = 'test2';
if(array.indexOf(element) === -1) {
array.push(element);
}
Append an array to another array
If you want to append an array to another array you can use the following snippet.
var a = [1,2,3];
var b = [4,5,6];
var c = a.concat(b);
alert (c);
In the example above a new array c[] is created. If you want to
append array b to array a just use:
a = a.concat(b);
Append an array to another array method 2
Javascript often provides for multiple solutions leading to the same result. Here is another example to append two arrays. This time the spread operator is used.
var a = [1,2,3];
var b = [4,5,6];
var c = [...a, ...b];
alert (c);
Here a new array (c) is constructed that contains all elements from array a and b.
If you want to append array a to array a just reverse the spread operator.
var c = [...b, ...a];
Append an array to another array method 3
The command array.push() allows us to push variables into an array. It is not widely known that you not only can add variables but also complete arrays.
let languages = ['C++', 'Javascript']
let extra = ['Lua', 'Python']
languages.push(extra)
alert(languages)
The command array.push() allows us to push variables into an array. It is not widely known that you not only can add variables but also complete arrays.
let languages = ['C++', 'Javascript']
let extra = ['Lua', 'Python']
languages.push(extra)
alert(languages)
Associative array
Normally an array's elements are adressed by their index number.
var array=["Basic", "C++"]
alert (array[1])
You can however create array elements that use a name as their index.
var learned=[]
learned["Basic"]="yes"
learned["C++"]="yes"
learned["Fortran"]="no"
alert(learned[1])
alert(learned["Basic"])
alert(learned[1]) will respond with "undefined"
alert(learned["Basic"]) will respond with "yes"
You can only adress the array's elements with their name and not by index number.
Normally an array's elements are adressed by their index number.
var array=["Basic", "C++"]
alert (array[1])
You can however create array elements that use a name as their index.
var learned=[]
learned["Basic"]="yes"
learned["C++"]="yes"
learned["Fortran"]="no"
alert(learned[1])
alert(learned["Basic"])
alert(learned[1]) will respond with "undefined"
alert(learned["Basic"]) will respond with "yes"
You can only adress the array's elements with their name and not by index number.
Build a 2 dimensional array
We can define a 2 dimensional array in a script. Here is a method that builds a 2 dimensional array when we do not know the dimensions in advance.
var testarray=[];
var row = 3;
var collumn = 3;
var count=0;
for(i = 0; i < row; i++)
{
for(j = 0; j<collumn; j++)
{
if(!testarray[i])
{
testarray[i] = [];
};
count++;
testarray[i][j] = count;
};
};
console.log(testarray);
We need to test in the for loop if testarray[i] exists. If not it has to be created first before we can fill it. This example fills the array in 3 rows with 3 colums filled with the figures 1 to 9 through increasing the count value.
Check for double elements in an array
There is a simple method to test if there are double elements in an array. With a for loop 'walk' through the array and test for eacht element if indexOf(element) is the same as lastIndexOf(element). If the first ansd last indexes are the same then it is the same element.
var testarray = ["Luc", "Volders", 2021, "Luc"];
function nodoubles(){
for(var i = 0; i < testarray.length; i++){
var test = testarray[i];
var firstIndex = testarray.indexOf(test);
var lastIndex = testarray.lastIndexOf(test);
if(firstIndex !== lastIndex){
return false;
};
};
return true;
};
alert(nodoubles(testarray));
The alert will show false in this example as my name occurs two times.
Check for double elements in an array 2
There are more ways to skin a cat and so has Javascript often multiple solutions for a problem. We are again going to test wether an array has double elements but in a different way. Using new Set(array) we convert an array into a set where the doubles are automatically removed. We can convert the set back into an array with [...set]. Combining these two makes a new array where the doubles have been removed. Now we only have to compare the length of both arrays to see if the original one has doubles.
var test = ["Luc", "Volders", 2021, "Luc"];
var newtest = [...new Set(test)]
if (newtest.length !== test.length) {alert("there are double elements")}
Convert an array with strings to an array with numbers
Here is a quick way to convert an array filled with strings to an array with numbers.
var stringarray = ["18", "20", "19"] ;
var numberarray = Array.from(stringarray, Number);
alert(numberarray);
Here a new array is created. If you do not want that you can use the same array name:
var stringarray = Array.from(stringarray, Number);
Here is a quick way to convert an array filled with strings to an array with numbers.
var stringarray = ["18", "20", "19"] ;
var numberarray = Array.from(stringarray, Number);
alert(numberarray);
Here a new array is created. If you do not want that you can use the same array name:
var stringarray = Array.from(stringarray, Number);
Convert an array with strings to an array with numbers 2
An array with strings can be converted to an array with numbers with the map() dunction. Here is an example.
var array = ["1", "2", "3", "4"].map(i=>Number(i));
console.log(array);
An array with strings can be converted to an array with numbers with the map() dunction. Here is an example.
var array = ["1", "2", "3", "4"].map(i=>Number(i));
console.log(array);
Convert an array to only strings
Here is a simple method to convert an array to an array
with only string elements.
var numbers = [ 1, 6, "a", 4, 8, "b", 5, 2];
numbers = numbers.map(String);
alert (typeof numbers[2]);
Here is a simple method to convert an array to an array
with only string elements.
var numbers = [ 1, 6, "a", 4, 8, "b", 5, 2];
numbers = numbers.map(String);
alert (typeof numbers[2]);
Convert an array with numbers to an array with strings
Let us do the reverse from the previous snippet. Convert an array with numbers to an array with strings.
var numberarray = [18, 20, 19] ;
var stringarray = Array.from(numberarray, String);
alert(stringarray);
Here also a new array is created. If you do not want that just use the same array.
var chain = [18, 20, 19] ;
var chain = Array.from(chain, String);
Let us do the reverse from the previous snippet. Convert an array with numbers to an array with strings.
var numberarray = [18, 20, 19] ;
var stringarray = Array.from(numberarray, String);
alert(stringarray);
Here also a new array is created. If you do not want that just use the same array.
var chain = [18, 20, 19] ;
var chain = Array.from(chain, String);
Convert an array to an CSV string
CSV files are often used for transferring data between programs with different file formats. Spreadsheets for example import CSV files. Using the next snippet we can convert an array to an CSV string.
var temperatures = ["jan", 10.5, "feb", 16.3, "mrt", 2.1];
var csvstring = temperatures.join(",");
alert(csvstring);
Convert an array to a string
Here is a quick way to convert an array to a string.
testarray = [1, 2, 3, 4];
teststring = testarray + "";
alert(teststring);
alert(typeof teststring);
This works also with multidimensional arrays and arrays with strings.
Convert an array to a string 2
Here is another method to convert an array to a string.
var myArray=['C++', 'Javascript', 'Python'];
stringtest=myArray.join(' ');
alert(stringtest)
alert(typeof stringtest)
In this case myArray.join(' ') joins all the array elements in a string and puts spaces between them
Here is another method to convert an array to a string.
var myArray=['C++', 'Javascript', 'Python'];
stringtest=myArray.join(' ');
alert(stringtest)
alert(typeof stringtest)
In this case myArray.join(' ') joins all the array elements in a string and puts spaces between them
Convert an array to an object
The command Object.assign() makes it very easy to convert an array to an object. The next example shows hot to use it.
const names = ['Basic', 'C++', 'Javascript', 'Lua'];
var obj = Object.assign({}, names);
console.log(obj);
The command Object.assign() makes it very easy to convert an array to an object. The next example shows hot to use it.
const names = ['Basic', 'C++', 'Javascript', 'Lua'];
var obj = Object.assign({}, names);
console.log(obj);
Convert an array to an object 2
An easy method to convert an array to an object is using the spread operator. Here is how it's done.
var names = ['Basic', 'C++', 'Javascript', 'Lua'];
objectnames={...names}
console.log(objectnames)
An easy method to convert an array to an object is using the spread operator. Here is how it's done.
var names = ['Basic', 'C++', 'Javascript', 'Lua'];
objectnames={...names}
console.log(objectnames)
Convert an array with strings to an array with numbers
Here is a quick way to convert an array filled with strings to an array with numbers.
var stringarray = ["18", "20", "19"] ;
var numberarray = Array.from(stringarray, Number);
alert(numberarray);
A new array is created. If you do not want that you can use the same array name:
var stringarray = Array.from(stringarray, Number);
Convert an array with numbers to an array with strings
Let us do the reverse from the previous snippet. Convert an array with numbers to an array with strings.
var numberarray = [18, 20, 19] ;
var stringarray = Array.from(numberarray, String);
alert(stringarray);
Here also a new array is created. If you do not want that just use the same array.
var chain = [18, 20, 19] ;
var chain = Array.from(chain, String);
Copy an entire array
When we need a copy of an array we can do the following:
var testarray = [5, 6, 3, 4]
var copyarray = testarray
This might pose a problem as copyarray is not a full copy but a list of memoryadresses that refer to testarray. Therefore will any changes made in testarray also be made in copyarray.
To prevent this we can use 2 methods to make a full copy of an array:
var testarray = [5, 6, 3, 4];
var copyarray = testarray.slice();
The slice() command without any parameters uses the full array.
Another option is to use the spread operator:
var testarray = [5, 6, 3, 4];
var copyarray = [...testarray];
When we need a copy of an array we can do the following:
var testarray = [5, 6, 3, 4]
var copyarray = testarray
This might pose a problem as copyarray is not a full copy but a list of memoryadresses that refer to testarray. Therefore will any changes made in testarray also be made in copyarray.
To prevent this we can use 2 methods to make a full copy of an array:
var testarray = [5, 6, 3, 4];
var copyarray = testarray.slice();
The slice() command without any parameters uses the full array.
Another option is to use the spread operator:
var testarray = [5, 6, 3, 4];
var copyarray = [...testarray];
Copy an array 2
Next to the slice() method to copy an array you can also use the spread operator:
var testarray = [5, 6, 3, 4];
var copyarray = [...testarray];
This also creates a new array which is an exact copy of the original
Copy part of an array
If you need to copy a known part of an array you can use array.slice() as the next snippet shows.
var rooms = ["mancave", "attick", "living", "garage"]
var part = rooms.slice(0,2)
alert(part)
If you need to copy a known part of an array you can use array.slice() as the next snippet shows.
var rooms = ["mancave", "attick", "living", "garage"]
var part = rooms.slice(0,2)
alert(part)
Copy all even numbers into a new array
If you want to get all the even numbers in an array and copy them to a new array the next snippet shows how to do that.
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
var evenNumbers = numbers.filter(i => i %2 ==0 );
console.log(evenNumbers);
If you do not want to use arrow functions you can do it like this:
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
var evennumbers = numbers.filter(function(item) {
return (item % 2 == 0);
});
console.log(evennumbers);
If you want to get all the even numbers in an array and copy them to a new array the next snippet shows how to do that.
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
var evenNumbers = numbers.filter(i => i %2 ==0 );
console.log(evenNumbers);
If you do not want to use arrow functions you can do it like this:
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
var evennumbers = numbers.filter(function(item) {
return (item % 2 == 0);
});
console.log(evennumbers);
Copy the positive elements from an array in a new array
We have an array that is filled with positive and negative numbers. We want to copy the positive values to a new array. The next snippet shows how to do that.
var testarr = [87, -98, 3, -2, 123, -877, 22, -5, 23, -67]
var posarr = [];
for (var i=0; i<testarr.length; i++)
{
if (testarr[i] >0)
{
posarr.push(testarr[i]);
}
}
alert(posarr)
Start with building a new empty array. Next iterate over the old array and test each element if it it positive. If it is push() it into the new array.
Copy all even numbers into a new array
If you want to get all the even numbers in an array and copy them to a new array the next snippet shows how to do that.
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
var evenNumbers = numbers.filter(i => i %2 ==0 );
console.log(evenNumbers);
If you do not want to use arrow functions you can do it like this:
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
var evennumbers = numbers.filter(function(item) {
return (item % 2 == 0);
});
console.log(evennumbers);
If you want to get all the even numbers in an array and copy them to a new array the next snippet shows how to do that.
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
var evenNumbers = numbers.filter(i => i %2 ==0 );
console.log(evenNumbers);
If you do not want to use arrow functions you can do it like this:
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
var evennumbers = numbers.filter(function(item) {
return (item % 2 == 0);
});
console.log(evennumbers);
Count the unique items in an array
You might want to know how many unique items there are in an array. The following snippet makes an object from an array with the amount of unique items
var array = ["Javascript", "Python", "Javascript", "C++"];
var unique = arr => {
const count = {};
for (var i = 0; i < array.length; i++) {
count[arr[i]] = 1 + (count[arr[i]] || 0);
};
return count;
};
alert(JSON.stringify(unique(array)));
Alert wil show : { Javascript: 2, Python: 1, "C++": 1 }
You might want to know how many unique items there are in an array. The following snippet makes an object from an array with the amount of unique items
var array = ["Javascript", "Python", "Javascript", "C++"];
var unique = arr => {
const count = {};
for (var i = 0; i < array.length; i++) {
count[arr[i]] = 1 + (count[arr[i]] || 0);
};
return count;
};
alert(JSON.stringify(unique(array)));
Alert wil show : { Javascript: 2, Python: 1, "C++": 1 }
Create an array and fill it with one value
If you do not want empty elements in an array at creation you
can use the next snippet.
var fillelements = 'Javascript tips - ';
var testarray = Array(3).fill(fillelements).join('');
alert (testarray);
The array is created with 3 elements and each element is filled with the variable testarray.
Create an array and fill it with x unique numbers
The next snippet shows how to create an array with a predefined number of elements that are unique and random between 1 and 100. Change while(arr.length < 10) in the number of elements you need and change Math.floor(Math.random() * 50) in the highest number you need.
var array = [];
while(array.length < 10){
var r = Math.floor(Math.random() * 50) + 1;
if(arr.indexOf(r) === -1) arr.push(r);
}
console.log(arr);
The next snippet shows how to create an array with a predefined number of elements that are unique and random between 1 and 100. Change while(arr.length < 10) in the number of elements you need and change Math.floor(Math.random() * 50) in the highest number you need.
var array = [];
while(array.length < 10){
var r = Math.floor(Math.random() * 50) + 1;
if(arr.indexOf(r) === -1) arr.push(r);
}
console.log(arr);
Delete clears an element
When you use delete to remove an element from an array the length of the rray does not change. The element is cleared but not removed.
let testarray = [ "one", "two", "three", "four"];
delete testarray[2];
alert testarray;
The alert will show "one", "two", ,"four"
The command delete clears the element but does not remove it. The array now contains one empty element. This actually is an advantage as the arrsys index does not alter.
Empty an array
The easiest and fastest way to empty an array is shown by the next snippet.
var testarray = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
testarray.length = 0;
Exchange two array elements
If you need to exchange two array elements the easiest way to do that is with destructuring like the following snippet shows.
var testarray = ['javascript', 'c++'];
[testarray[0], testarray[1]] = [testarray[1], testarray[0]];
console.log(testarray)
Exchange two array elements 2
If you need to swap two array elements you can do that with a helper varaible. Here is an example.
var helper = array[y];
array[y] = array[x];
array[x] = helper;
If you need to swap two array elements you can do that with a helper varaible. Here is an example.
var helper = array[y];
array[y] = array[x];
array[x] = helper;
Exchange array elements from different arrays
This tip uses the same method as the tip where two array elemets are exchanged. The difference is that we here exchzange the elements from 2 different arrays.
var testarray = ['javascript', 'c++'];
var testarray2 = ["python", "lua"];
[testarray[0], testarray2[0]] = [testarray2[0], testarray[0]];
console.log(testarray)
console.log(testarray2)
The output will be:
[ 'python', 'c++' ]
[ 'javascript', 'lua' ]
Fill an array with the numbers 0 till a max value
To fill an empty array with values from 0 to a maximum value we can use the following snippet:
var testarray = [];
var start = 90;
var maximum = 100-start;
for( var i=1; testarray.push(i++) < maximum;);
Fill an array with the numbers 0 till a maximum value 2
There is an easy way to fill an array with thye numbers from 0 to x. Just use the keys like this:
Array.from(Array(10).keys())
In this example the array will have the following contents [0,1,2,3,4,5,6,7,8,9]
There is an easy way to fill an array with thye numbers from 0 to x. Just use the keys like this:
Array.from(Array(10).keys())
In this example the array will have the following contents [0,1,2,3,4,5,6,7,8,9]
Filter even numbers from an array
The next snippet shows a function that filters the even numbers out of an array.
var array = [-3, -2, -1, 1, 2, 3];
var evennrs = array.filter(function(x) {
return x % 2 === 0;
})
console.log(evennrs);
The next snippet shows a function that filters the even numbers out of an array.
var array = [-3, -2, -1, 1, 2, 3];
var evennrs = array.filter(function(x) {
return x % 2 === 0;
})
console.log(evennrs);
Filter negative values from an array
You can use the filter command to remove negative numbersw from an array. The next snippet shows how.
var array = [18, -42, 21, 6, -50];
array = array.filter(larger => larger > -1);
console.log(array);
If you do not want to use the arrow functions you can use the normal function syntax like this:
var array = [18, -42, 21, 6, -50];
array = array.filter(function(x) { return x > -1; });
console.log(array);
You can use the filter command to remove negative numbersw from an array. The next snippet shows how.
var array = [18, -42, 21, 6, -50];
array = array.filter(larger => larger > -1);
console.log(array);
If you do not want to use the arrow functions you can use the normal function syntax like this:
var array = [18, -42, 21, 6, -50];
array = array.filter(function(x) { return x > -1; });
console.log(array);
Filter values from an array
The command filter() is an easy way to filter values out of an array. The next example creates a new array with only words from the old array that are longer as 3 letters.
var languages = ['C++', 'Basic', 'Javascript', 'Lua', 'Python'];
var result = languages.filter(word => word.length > 3);
alert(result);
The next line filters the word "Lua" from the same array
var result = languages.filter(word => word != "Lua");
The command filter() is an easy way to filter values out of an array. The next example creates a new array with only words from the old array that are longer as 3 letters.
var languages = ['C++', 'Basic', 'Javascript', 'Lua', 'Python'];
var result = languages.filter(word => word.length > 3);
alert(result);
The next line filters the word "Lua" from the same array
var result = languages.filter(word => word != "Lua");
Find an element in an array
Using .includes() is a fast method to check wether an array contains an element. Use it like this:
var testarray = ["aaa", "bbb", "ccc"]
if (testarray.includes("bbb"))
{
alert("bbb is found in the array");
}
To find where it is in the array you can use the following code.
where=testarray.indexOf("bbb");
alert(where);
Using .includes() is a fast method to check wether an array contains an element. Use it like this:
var testarray = ["aaa", "bbb", "ccc"]
if (testarray.includes("bbb"))
{
alert("bbb is found in the array");
}
To find where it is in the array you can use the following code.
where=testarray.indexOf("bbb");
alert(where);
Find an object in an array
If you need to search a certain object in an array with objects this is an easy method to do so.
var arr = [
{ name:"little", lang1:"Basic", lang2: "Lua" },
{ name:"much", lang1:"Javascript", lang2: "Python" }
];
var found = arr.find(test => test.name === 'much');
console.log(found);
In this example we search for an object with the key name "much"
If you need to search a certain object in an array with objects this is an easy method to do so.
var arr = [
{ name:"little", lang1:"Basic", lang2: "Lua" },
{ name:"much", lang1:"Javascript", lang2: "Python" }
];
var found = arr.find(test => test.name === 'much');
console.log(found);
In this example we search for an object with the key name "much"
Find the missing numbers in an integer array
There is an array filled with integer numbers and some numbers are missing. The next snippet shows how to find the missing numbers.
var array = [11,12,15, 17];
start = 10;
end = 20;
missing = [];
for (let i = start; i <= end+1; i++) {
if (array.indexOf(i) === -1) {
missing.push(i)
}
}
console.log(missing)
There is an array filled with integer numbers and some numbers are missing. The next snippet shows how to find the missing numbers.
var array = [11,12,15, 17];
start = 10;
end = 20;
missing = [];
for (let i = start; i <= end+1; i++) {
if (array.indexOf(i) === -1) {
missing.push(i)
}
}
console.log(missing)
Flatten an array
If you need to make a single dimension array from a multidemensional array (flatten the array) there are two methods you can use. You can use array = array.flat() or array =[].concat(...array). To demonstrate these is here a snippet that shows how to use these commands.
var arr = ["Javascript", "Python", ["Basic", "Lua"]];
array = arr.flat();
alert(array)
Or you can use:
array = [].concat(...arr)
alert(array)
If you need to make a single dimension array from a multidemensional array (flatten the array) there are two methods you can use. You can use array = array.flat() or array =[].concat(...array). To demonstrate these is here a snippet that shows how to use these commands.
var arr = ["Javascript", "Python", ["Basic", "Lua"]];
array = arr.flat();
alert(array)
Or you can use:
array = [].concat(...arr)
alert(array)
Functions inside an array
Just like we can put a function inside an array we can also put it into an array element. De function can then be called with: arrayname[index](). Here is a snippet that demonstrates this.
var a=5;
var b=6;
var array_of_functions =
[
function() { c=a*b; return c },
function() { alert('a string') },
function() { alert('another string') },
function() { alert('the third string') }
]
d=array_of_functions[0]();
alert(d);
array_of_functions[1]();
In the script alert(d) wil call the function in the first array element (0) and answer the result which is 30. array_of_functions[1]() will call the function in array element [1] The functions are executed because of the () after the array element.
Get a random value out of an array
If we have an array filled with names, data, or other values and we need to pick a random value out of that array we can do that with the following script.
function chosename(names) {
const randomnumber = Math.floor(Math.random() * names.length);
return names[randomnumber];
}
names = ["Javascript", "C++", "Python", "Lua", "Basic"];
alert(chosename(names));
Get an element from the end of an array
To get the last element from an array you can use array.slice(-1)
let array = [10, 20, 30, 40, 50];
document.write(array.slice(-1));
By using array.slice(-3) you will get the last 3 elements.
let array = [10, 20, 30, 40, 50];
document.write(array.slice(-3));
A new array is made that contains only the last 3 elements of the original one.
When you just need the third last element from an arry you can do that with the following snippet.
let array = [10, 20, 30, 40, 50];
document.write(array.slice(-3)[0]);
Get the diagonal values out of a 2 dimensional array
If we have a 2 dimensional array and we need the values of the diagonal elements we can do that with a for loop. However we need to increase the values of the x and y co-ordinates at the same time. This can be done by using the comma operator in the for declaration.
var testarray = [
[1,2,3],
[4,5,6],
[7,8,9]
];
alert(testarray);
var x=0;
var y=0;
for(x = 0,y = 0; x < testarray.length; x++, y++)
{
alert(testarray[x][y]);
}
As you can see the x and y values are increased in the for loop at the same time. The alert will show the values 1, 5 and 9
Get elements that occur in two arrays
Th next snippet shows how to get elements out of two arrays that only occur in one of these arrays.
testarray1 = [1,1,2,3,4,4];
testarray2 = [1,3,4,5,8];
newarray1 = Array.from(new Set(testarray1));
newarray2 = Array.from(new Set(testarray2));
result = newarray1.filter(item => newarray2.includes(item));
alert(result);
Get elements that occur in array 1 but not in array 2
By changing just one thing in the previous snippet we can test which elements are found in array 1 that do not occur in array 2.
testarray1 = [1,1,2,3,4,4];
testarray2 = [1,3,4,5,8];
newarray1 = Array.from(new Set(testarray1));
newarray2 = Array.from(new Set(testarray2));
result = newarray1.filter(item => !newarray2.includes(item));
alert(result);
We only have to change newarray2.includes(item) in !newarray2.includes(item)
Get the last element of an array
Use array.length-1 as the index to obtain the last element of an array.
var testarray = ["jan", "feb", "mar", "apr"];
var last = testarray[testarray.length-1];
alert(last)
Get the last x elements out of an array
the previous tip showed how to get the last element out of an array. Another method to get the last element is using array.slice(-1). We can use this also to get the last x elements out of an array.
var a;
var b;
var c;
var testarray = [0, 1, 2, 3, 4, 5, 6, 7] ;
[a, b, c]= testarray.slice(-3);
alert(b);
The above snippet shows how to get the last 3 elements out of an array and at the same time put them into 3 new elements using array destructuring.
the previous tip showed how to get the last element out of an array. Another method to get the last element is using array.slice(-1). We can use this also to get the last x elements out of an array.
var a;
var b;
var c;
var testarray = [0, 1, 2, 3, 4, 5, 6, 7] ;
[a, b, c]= testarray.slice(-3);
alert(b);
The above snippet shows how to get the last 3 elements out of an array and at the same time put them into 3 new elements using array destructuring.
Get the lowest and highest values in an array
We can sort an array to find the lowest and highest values but this alters the array itself. To find the lowest and highest values without altering the array use the following snippet:
const numbers = ["1", "2", 1.5, 6.7];
var max = Math.max(...numbers);
var min = Math.min(...numbers);
alert("Lowest = " + min + " Highest = " + max)
We can sort an array to find the lowest and highest values but this alters the array itself. To find the lowest and highest values without altering the array use the following snippet:
const numbers = ["1", "2", 1.5, 6.7];
var max = Math.max(...numbers);
var min = Math.min(...numbers);
alert("Lowest = " + min + " Highest = " + max)
javascript code in an array element
You can put almost anything in an array. Here is an example that puts code
in an array and then makes that code work by using eval.
var i;
var text = "";
var array1 = [
5,
6,
"hello 1 " ,
"hello 2" ,
'for (i = 0; i < array1.length-1; i++) {text += array1[i] + "<br>";}'
];
var test = array1[4];
document.write(eval(test));
You can put almost anything in an array. Here is an example that puts code
in an array and then makes that code work by using eval.
var i;
var text = "";
var array1 = [
5,
6,
"hello 1 " ,
"hello 2" ,
'for (i = 0; i < array1.length-1; i++) {text += array1[i] + "<br>";}'
];
var test = array1[4];
document.write(eval(test));
Move an element in an array to a new index
To move an element in an array to a new position we first remove the element and then put it at its new place with array.splice(). Here is how to do that.
var array = [ "Lua", "Basic", "C++", "Javascript", "Python"]
location = array.splice(0,1);
array.splice(3,0, location);
alert(array)
First we remove the element at location 0 and put it in the variable location. The array then looks like Basic, C++, Javascripy, Python. Then we put the variable location at the 4th place in the array.
To move an element in an array to a new position we first remove the element and then put it at its new place with array.splice(). Here is how to do that.
var array = [ "Lua", "Basic", "C++", "Javascript", "Python"]
location = array.splice(0,1);
array.splice(3,0, location);
alert(array)
First we remove the element at location 0 and put it in the variable location. The array then looks like Basic, C++, Javascripy, Python. Then we put the variable location at the 4th place in the array.
Move an element to the first location in an array
If you want to move an element from an array to the first location then you can do that with array.splice() and array.unshift(). Here is an example.
var array = ["C++", "Javascript", "Lua","Basic", "Python"]
var position = 3;
array.unshift(array.splice(position, 1)[0]);
alert(array)
If you want to move an element from an array to the first location then you can do that with array.splice() and array.unshift(). Here is an example.
var array = ["C++", "Javascript", "Lua","Basic", "Python"]
var position = 3;
array.unshift(array.splice(position, 1)[0]);
alert(array)
Optimising array loops
We often have toi iterate through an array without knowing the length of the array. We can get the length with array.length but this value is calculated every time anew:
var testarray = [ 15,8,9,12,7,6];
var i;
for (i = 0; i<testarray.length; i++)
{
document.write(testarray[i] + " ");
}
In this program the loop has to test every time wether i is less then testarray.length. Using this with a small array like above is not a big issue. When using this in an array with 1000's of elements this slows the iteration down. It is much faster to calculate array.length once and put it in a seperate variable which we will use to iterate the array.
var testarray = [ 15,8,9,12,7,6];
aantal = testarray.length
var i;
for (i = 0; i<aantal; i++)
{
document.write(testarray[i]+" ");
}
We often have toi iterate through an array without knowing the length of the array. We can get the length with array.length but this value is calculated every time anew:
var testarray = [ 15,8,9,12,7,6];
var i;
for (i = 0; i<testarray.length; i++)
{
document.write(testarray[i] + " ");
}
In this program the loop has to test every time wether i is less then testarray.length. Using this with a small array like above is not a big issue. When using this in an array with 1000's of elements this slows the iteration down. It is much faster to calculate array.length once and put it in a seperate variable which we will use to iterate the array.
var testarray = [ 15,8,9,12,7,6];
aantal = testarray.length
var i;
for (i = 0; i<aantal; i++)
{
document.write(testarray[i]+" ");
}
Process two arrays of different length
If we want to process two arrays with different lengths we need to work with the shortest length to not get into trouble. In the next example we add the elements of to arrays which have different lengths. The solution is a new array with the length of the shortest array.
var shortarray = [1, 2, 3, 4, 5];
var longarray = [3, 6, 9, 2, 1, 8, 7, 3];
var additionarray = [];
for (var i = 0; i < Math.min(shortarray.length, longarray.length); i++)
{
additionarray[i] = arr[i] + arr1[i];
}
alert(additionarray);
Math.min(kortarray.length, langarray.length) makes sure that the loop processes only as much elements that are present in the shortest array.
If we want to process two arrays with different lengths we need to work with the shortest length to not get into trouble. In the next example we add the elements of to arrays which have different lengths. The solution is a new array with the length of the shortest array.
var shortarray = [1, 2, 3, 4, 5];
var longarray = [3, 6, 9, 2, 1, 8, 7, 3];
var additionarray = [];
for (var i = 0; i < Math.min(shortarray.length, longarray.length); i++)
{
additionarray[i] = arr[i] + arr1[i];
}
alert(additionarray);
Math.min(kortarray.length, langarray.length) makes sure that the loop processes only as much elements that are present in the shortest array.
Put the array values in a random sequence
Often an array is sorted. If you want the values in an array in a random sequence you can use the following snippet.
var testarray = [0,1,2,3,4,5,6,7,8,9];
function randomise(array) {
var i, j, temp;
for (i = array.length - 1; i > 0; i--) {
j = Math.floor(Math.random() * (i + 1));
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
alert(randomise(testarray));
Often an array is sorted. If you want the values in an array in a random sequence you can use the following snippet.
var testarray = [0,1,2,3,4,5,6,7,8,9];
function randomise(array) {
var i, j, temp;
for (i = array.length - 1; i > 0; i--) {
j = Math.floor(Math.random() * (i + 1));
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
alert(randomise(testarray));
Put the array values in a random sequence 2
We can shuffle array elements with the following snippet.
var testarray = [0,1,2,3,4,5,6,7,8,9];
testarray.sort(function()
{
return Math.random() - .5
});
alert(testarray);
This will wotk with arrays filled with numbers and arrays filled with strings.
We can shuffle array elements with the following snippet.
var testarray = [0,1,2,3,4,5,6,7,8,9];
testarray.sort(function()
{
return Math.random() - .5
});
alert(testarray);
This will wotk with arrays filled with numbers and arrays filled with strings.
Que simulation
A que is a lineup. Compared to real life a lineup where first come, first served. Ques are sometimes used in programs and they are called on a First-In-First-Out base. This can easily be achieved with creating an array and using the array functions array.push() and array.shift()
var que = [];
var vara;
function inque(data)
{
que.push(data);
}
function fromque()
{
return que.shift();
}
Here we created two functions being inque() that puts data into the que and fromque() which removes the first in line. This can be shortened with arrow functions:
inque=(data)=>que.push(data);
fromque=()=>que.shift();
We can use the que by calling the finctions with a parameter:
inque(6);
inque(5);
inque(3);
alert("de que bevat nu " + que);
vara = fromque();
alert("First In First Out " + vara);
alert("blijft over " + que);
A que is a lineup. Compared to real life a lineup where first come, first served. Ques are sometimes used in programs and they are called on a First-In-First-Out base. This can easily be achieved with creating an array and using the array functions array.push() and array.shift()
var que = [];
var vara;
function inque(data)
{
que.push(data);
}
function fromque()
{
return que.shift();
}
Here we created two functions being inque() that puts data into the que and fromque() which removes the first in line. This can be shortened with arrow functions:
inque=(data)=>que.push(data);
fromque=()=>que.shift();
We can use the que by calling the finctions with a parameter:
inque(6);
inque(5);
inque(3);
alert("de que bevat nu " + que);
vara = fromque();
alert("First In First Out " + vara);
alert("blijft over " + que);
Reverse an array
To reverse an array you simply use: array.reverse(). If you want to keep the original array you can define a new array while reversing it like this:
var array=[1,2,3,4,5,6]
var newarray = array.reverse()
alert(newarray)
To reverse an array you simply use: array.reverse(). If you want to keep the original array you can define a new array while reversing it like this:
var array=[1,2,3,4,5,6]
var newarray = array.reverse()
alert(newarray)
Reversing an array
There might be a script in which you need to reverse an array. The easiest method is to use array.reverse() This however does not make a new array but reverses the original one. And it might be possible that you want to keep the original array next to the reversed one. The following does not work:
var testarray = [1, 2, 3, 4, 5];
testarray2 = testarray.reverse();
alert("testarray 2 : " + testarray2);
testarray2[1]=7;
alert("testarray : " + testarray);
Running this script will show that changing an element in testarray2 also changes the original array. This is because testarray2 is a reference and not a real new array.
To reverse an array in a real new array you can use the following solution:
var testarray = [1, 2, 3, 4, 5];
testarray2 = testarray.slice().reverse();
alert(testarray2);
alert("testarray 2 : " + testarray2);
testarray2[1]=7;
alert("testarray : " + testarray);
When running this script you will see that testarray and testarry2 now are completely different arrays and changing a value in one of them will nof affect the other one.
There might be a script in which you need to reverse an array. The easiest method is to use array.reverse() This however does not make a new array but reverses the original one. And it might be possible that you want to keep the original array next to the reversed one. The following does not work:
var testarray = [1, 2, 3, 4, 5];
testarray2 = testarray.reverse();
alert("testarray 2 : " + testarray2);
testarray2[1]=7;
alert("testarray : " + testarray);
Running this script will show that changing an element in testarray2 also changes the original array. This is because testarray2 is a reference and not a real new array.
To reverse an array in a real new array you can use the following solution:
var testarray = [1, 2, 3, 4, 5];
testarray2 = testarray.slice().reverse();
alert(testarray2);
alert("testarray 2 : " + testarray2);
testarray2[1]=7;
alert("testarray : " + testarray);
When running this script you will see that testarray and testarry2 now are completely different arrays and changing a value in one of them will nof affect the other one.
Remove and modify array elements with one command
With array splice(x,y) we can remove items from an array starting at location x and remove y items.
Lesser know is that we can add elements to this command to replace the removed elements with new ones. You can do that as follows:
var task = ["We", "are", "starting", "programming", "tomorrow"];
task.splice(0, 4, "I", "am", "going", "to", "buy", "Javascript", "tips");
console.log(task);
Notice that we removed 4 elements and added 7 elements.
With array splice(x,y) we can remove items from an array starting at location x and remove y items.
Lesser know is that we can add elements to this command to replace the removed elements with new ones. You can do that as follows:
var task = ["We", "are", "starting", "programming", "tomorrow"];
task.splice(0, 4, "I", "am", "going", "to", "buy", "Javascript", "tips");
console.log(task);
Notice that we removed 4 elements and added 7 elements.
Remove duplicates from an array
If you want to clean up an array by removing duplicates, the following snippet shows an easy solution.
var array = ["a", "a", "b", "c", "c", "d", "e"];
array = [...new Set(array)];
alert (array);
This works with arrays with text, numbers and mixed types.
In the above example the original array is altered. If you want to keep the original array and have a new array in which the duplicates are removed the solution is imple: just give it another name:
var array = ["a", "a", "b", "c", "c", "d", "e"];
newarray = [...new Set(array)];
alert (newarray);
If you want to clean up an array by removing duplicates, the following snippet shows an easy solution.
var array = ["a", "a", "b", "c", "c", "d", "e"];
array = [...new Set(array)];
alert (array);
This works with arrays with text, numbers and mixed types.
In the above example the original array is altered. If you want to keep the original array and have a new array in which the duplicates are removed the solution is imple: just give it another name:
var array = ["a", "a", "b", "c", "c", "d", "e"];
newarray = [...new Set(array)];
alert (newarray);
Remove duplicates from two arrays
If you want to combine two arrays into one and remove the duplicates this is how you can do that:
var first = ["Javascript", "Lua", "Python"];
var second = ["C++", "Basic", "Lua", "Python"];
var new2= [...first, ...second];
var new3=[...new Set(new2)]
alert(new3)
First we combine the two arrays into one with the ...spread operator. Then we take out the double entries by the new Set command.
If you want to combine two arrays into one and remove the duplicates this is how you can do that:
var first = ["Javascript", "Lua", "Python"];
var second = ["C++", "Basic", "Lua", "Python"];
var new2= [...first, ...second];
var new3=[...new Set(new2)]
alert(new3)
First we combine the two arrays into one with the ...spread operator. Then we take out the double entries by the new Set command.
Remove double entries from an array
There is a special kind of an array called a set. A set does not accept double entries. So the easiest method to remove double entries out of an array is to convert the array into a set and then convert it back to an array. The next snippet shows how to do that.
var testarray = ["Javascript", "tips", "tips", "Luc", "Luc", "Volders"];
var nodoubles = Array.from(new Set(testarray));
alert(nodoubles);
Another way is to use the spread (...) operator like this:
var testarray = ["Javascript", "tips", "tips", "Luc", "Luc", "Volders"];
var nodoubles = [...new Set(testarray)];
alert(nodoubles);
There is a special kind of an array called a set. A set does not accept double entries. So the easiest method to remove double entries out of an array is to convert the array into a set and then convert it back to an array. The next snippet shows how to do that.
var testarray = ["Javascript", "tips", "tips", "Luc", "Luc", "Volders"];
var nodoubles = Array.from(new Set(testarray));
alert(nodoubles);
Another way is to use the spread (...) operator like this:
var testarray = ["Javascript", "tips", "tips", "Luc", "Luc", "Volders"];
var nodoubles = [...new Set(testarray)];
alert(nodoubles);
Remove elements from an array
slice is used to remove elements from an array. slice accepts 2 parameters. The first one is the index where to start and the second one is the number to be removed. Please be aware that counting starts at 0.
array = [1, 2, 3, 4, 5, 6, 7, 8, 9]
var begin = 2;
var number = 3;
arr.splice(begin, number);
alert(arr)
This example removes the figures 3,4 and 5. Removing starts at element 2, which is figure 3 as we start counting at 0, and removes 2 elements.
slice is used to remove elements from an array. slice accepts 2 parameters. The first one is the index where to start and the second one is the number to be removed. Please be aware that counting starts at 0.
array = [1, 2, 3, 4, 5, 6, 7, 8, 9]
var begin = 2;
var number = 3;
arr.splice(begin, number);
alert(arr)
This example removes the figures 3,4 and 5. Removing starts at element 2, which is figure 3 as we start counting at 0, and removes 2 elements.
Remove falsey values from an array
Here is a simple solution for removing falsey (0, undefined, null, false) values from an array.
var testarray = ["a", "test", 150 ,225 ,233, undefined, 4, false, ""]
var testarray = testarray.filter(Boolean);
console.log(testarray);
The array wil now be: [ 'a', 'test', 150, 225, 233, 4 ]
Just be carefull because this also removes 0.
Here is a simple solution for removing falsey (0, undefined, null, false) values from an array.
var testarray = ["a", "test", 150 ,225 ,233, undefined, 4, false, ""]
var testarray = testarray.filter(Boolean);
console.log(testarray);
The array wil now be: [ 'a', 'test', 150, 225, 233, 4 ]
Just be carefull because this also removes 0.
Remove one or more elements from an array
In our program we have an raary that contains the next elements:
var testarray = [ "jan","feb","mar","apr","may","jun"];
If we want to remove "mar" from the array we have to know it's location. In this case that is 2. To remove "mar" from the array we can use the following command:
array.splice(2, 1);
This removes 1 element at location 2.
If we do not know the location but know that we want to remove the value "apr" we can use the following lines:
var toberemoved = "apr";
for(var i = testarray.length - 1; i >= 0; i--)
{
if(testarray[i] === toberemoved)
{
testarray.splice(i, 1);
}
}
The array is iterated and a test is performed that compares each element with the variable toberemoved. If a match is found the element is removed.
In the above example the array is shortened with 1 element. there are only five elements left in the array and that can influence other parts of your program.
If you do not want the number of elements to be shortened you can empty the location in the array. In that case replace testarray.splice(i, 1); by:
delete array[i];
The array wil then be as follows:
[ "jan","feb","mar",,"may","jun"];
Now we have an array with an empty element in it. This element contains "undefined" which is something that is not desirable in all cases. If you do not want empty elements in your array you can replace "apr" by a special character like "*". To achieve that use in stead of testarray.splice(i, 1); the following line:
testarray[i]="*";
In our program we have an raary that contains the next elements:
var testarray = [ "jan","feb","mar","apr","may","jun"];
If we want to remove "mar" from the array we have to know it's location. In this case that is 2. To remove "mar" from the array we can use the following command:
array.splice(2, 1);
This removes 1 element at location 2.
If we do not know the location but know that we want to remove the value "apr" we can use the following lines:
var toberemoved = "apr";
for(var i = testarray.length - 1; i >= 0; i--)
{
if(testarray[i] === toberemoved)
{
testarray.splice(i, 1);
}
}
The array is iterated and a test is performed that compares each element with the variable toberemoved. If a match is found the element is removed.
In the above example the array is shortened with 1 element. there are only five elements left in the array and that can influence other parts of your program.
If you do not want the number of elements to be shortened you can empty the location in the array. In that case replace testarray.splice(i, 1); by:
delete array[i];
The array wil then be as follows:
[ "jan","feb","mar",,"may","jun"];
Now we have an array with an empty element in it. This element contains "undefined" which is something that is not desirable in all cases. If you do not want empty elements in your array you can replace "apr" by a special character like "*". To achieve that use in stead of testarray.splice(i, 1); the following line:
testarray[i]="*";
Remove the first x elements from an arry
Using array.slice(x ,1) we can remove the element woth index x from the array. But if we use array.slice(x) this wil remove the first x elements from the array. The next snippet gives an example.
array = [1,2,3,4,5]
array=array.slice(2)
alert(array) // => [3, 4, 5]
Using array.slice(x ,1) we can remove the element woth index x from the array. But if we use array.slice(x) this wil remove the first x elements from the array. The next snippet gives an example.
array = [1,2,3,4,5]
array=array.slice(2)
alert(array) // => [3, 4, 5]
Remove the last x elements from an array
To remove the last x elements from an array you can use the next snippet.
var testarray = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
testarray = testarray.slice(0,6);
alert(testarray);
The alert will show the figures 0 till 5 because they are the only 6 elements left in the array.
To remove the last x elements from an array you can use the next snippet.
var testarray = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
testarray = testarray.slice(0,6);
alert(testarray);
The alert will show the figures 0 till 5 because they are the only 6 elements left in the array.
Remove the last x elements from an array 2
Here is another method to remove the last x elements from an array.
let testarray = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
testarray.length = 6;
alert(testarray);
Here the alert will also show the figures 0 to 5 because they are the only 6 elements left over from the array.
Here is another method to remove the last x elements from an array.
let testarray = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
testarray.length = 6;
alert(testarray);
Here the alert will also show the figures 0 to 5 because they are the only 6 elements left over from the array.
Rotate the last array element to the front
To bring the last array element to the front use array.pop() to remove it from the back and array.unshift() to push it into the front.
testarr = [1,2,3,4];
testarr.unshift(testarr.pop())
alert(testarr) // =>4123
To bring the last array element to the front use array.pop() to remove it from the back and array.unshift() to push it into the front.
testarr = [1,2,3,4];
testarr.unshift(testarr.pop())
alert(testarr) // =>4123
Rotate the first array element to the back
To bring the first array element to the back it has to be removed with array.shift() and pushed at the back with array.push().
testarr = [1,2,3,4];
testarr.push(testarr.shift())
alert(testarr) // =>2,3,4,1
To bring the first array element to the back it has to be removed with array.shift() and pushed at the back with array.push().
testarr = [1,2,3,4];
testarr.push(testarr.shift())
alert(testarr) // =>2,3,4,1
Remove the second last element from an array
To remove the second last element from an array use this snippet:
array = [1,2,3,4]
seclast = array.splice(array.length -2,1)
alert(seclast)
To remove the second last element from an array use this snippet:
array = [1,2,3,4]
seclast = array.splice(array.length -2,1)
alert(seclast)
Search a string in a multidimensional array
We can search a string inside an array with includes(). However this does not function in a multi dimensional array like the next example shows.
var names = ['Basic', 'Python', ['C++', 'Javascript', ['Lua']]];
alert(names.includes("Lua"));
The alert shows "false" as includes() does not work inside a multi-dimensional array.
The solution is to flatten the array with JSON.stringify and then search for the string.
var names = ['Basic', 'Python', ['C++', 'Javascript', ['Lua']]];
function isinside(names,lookfor)
{
return JSON.stringify(names).includes(lookfor);
}
trueornot = isinside(names,"Lua");
alert(trueornot);
Now the alert shows "true"
We can search a string inside an array with includes(). However this does not function in a multi dimensional array like the next example shows.
var names = ['Basic', 'Python', ['C++', 'Javascript', ['Lua']]];
alert(names.includes("Lua"));
The alert shows "false" as includes() does not work inside a multi-dimensional array.
The solution is to flatten the array with JSON.stringify and then search for the string.
var names = ['Basic', 'Python', ['C++', 'Javascript', ['Lua']]];
function isinside(names,lookfor)
{
return JSON.stringify(names).includes(lookfor);
}
trueornot = isinside(names,"Lua");
alert(trueornot);
Now the alert shows "true"
Search an array
There are several ways to search items in an array. The method presented here is to use the filter() function. The next snippet demonstrates this.
var languages = ["Basic", "C++", "Javascript", "Lua", "Python"];
const search = (lookfor, source) =>
{
let query = lookfor.toLowerCase();
return source.filter(item => item.toLowerCase().indexOf(query) >= 0);
}
console.log(search("as", languages));
This example searches for "as" in the array languages and finds Basic and Javascript.
There are several ways to search items in an array. The method presented here is to use the filter() function. The next snippet demonstrates this.
var languages = ["Basic", "C++", "Javascript", "Lua", "Python"];
const search = (lookfor, source) =>
{
let query = lookfor.toLowerCase();
return source.filter(item => item.toLowerCase().indexOf(query) >= 0);
}
console.log(search("as", languages));
This example searches for "as" in the array languages and finds Basic and Javascript.
Search and remove an item in an array
The next snippet shows how to search and remove an item from an array. The element is searched with indexOf() and at the same time removed with slice()
var testarray = ["jan", "feb", "march", "apr", "may"];
var index = testarray.indexOf("apr");
if (index !== -1) array.splice(index,1)
you can combine this in one statement:
testarray.splice (testarray.indexOf("apr"), 1);
The next snippet shows how to search and remove an item from an array. The element is searched with indexOf() and at the same time removed with slice()
var testarray = ["jan", "feb", "march", "apr", "may"];
var index = testarray.indexOf("apr");
if (index !== -1) array.splice(index,1)
you can combine this in one statement:
testarray.splice (testarray.indexOf("apr"), 1);
Shuffle the array elements
If you have an ordered array and need to mix the elements you can use the following command:
array.sort(() => Math.random() - 0.5);
If you do not want to use the arrow notation:
array.sort(function() { return 0.5 - Math.random() });
If you have an ordered array and need to mix the elements you can use the following command:
array.sort(() => Math.random() - 0.5);
If you do not want to use the arrow notation:
array.sort(function() { return 0.5 - Math.random() });
Skip array element with destructuring
While converting an array to variables with the destructering method you can skip array elements like this.
var array = ['Basic', 'C++', 'Javascript'];
var [x, , z] = array;
console.log(x);
console.log(z);
While converting an array to variables with the destructering method you can skip array elements like this.
var array = ['Basic', 'C++', 'Javascript'];
var [x, , z] = array;
console.log(x);
console.log(z);
Sort a multidemisional array
We can sort a two dimensional array on its index
var array = [[12, 'AAA'], [12, 'BBB'], [12, 'CCC'],[28, 'DDD'], [18, 'CCC'],[12, 'DDD'],[18, 'CCC'],[28, 'DDD'],[28, 'DDD'],[58, 'BBB'],[68, 'BBB'],[78, 'BBB']];
array.sort(function(a,b) {
return a[0]-b[0]
});
In this example we sort on index [0] which are the numbers. If you want to sort on the second index (the words) use this code: return (a[1] < b[1]) ? -1 : 1;
We can sort a two dimensional array on its index
var array = [[12, 'AAA'], [12, 'BBB'], [12, 'CCC'],[28, 'DDD'], [18, 'CCC'],[12, 'DDD'],[18, 'CCC'],[28, 'DDD'],[28, 'DDD'],[58, 'BBB'],[68, 'BBB'],[78, 'BBB']];
array.sort(function(a,b) {
return a[0]-b[0]
});
In this example we sort on index [0] which are the numbers. If you want to sort on the second index (the words) use this code: return (a[1] < b[1]) ? -1 : 1;
Sort a 2d array on its second element
To sort a 2D array on it's second element use the next code:
var array = [[1, "Javascript"], [2, "Basic"], [3, "Lua"], [4, "C++"]];
array.sort(function (a, b) {
return a[1]>(b[1]);
});
alert(array) to edit.
To sort a 2D array on it's second element use the next code:
var array = [[1, "Javascript"], [2, "Basic"], [3, "Lua"], [4, "C++"]];
array.sort(function (a, b) {
return a[1]>(b[1]);
});
alert(array) to edit.
Sort an array according to the length of its elements
If you need to sort an array according to the length of its elements you can use the next snippet.
var textar = ["Python", "Javascript", "C++"];
function sortonlength()
{
var sorted = textar.sort(function(a, b)
{
return a.length - b.length;
})
return sorted;
};
alert(sortonlength(textar));
You can shorten this as follows.
textar.sort(function(a, b){return a.length - b.length});
If you are a fan of arrow functions you can use this:
textar.sort((x,y) => x.length - y.length);
If you need to sort an array according to the length of its elements you can use the next snippet.
var textar = ["Python", "Javascript", "C++"];
function sortonlength()
{
var sorted = textar.sort(function(a, b)
{
return a.length - b.length;
})
return sorted;
};
alert(sortonlength(textar));
You can shorten this as follows.
textar.sort(function(a, b){return a.length - b.length});
If you are a fan of arrow functions you can use this:
textar.sort((x,y) => x.length - y.length);
Sort an array by the dates in elements
You can nsort an array with numbers, letters, strings etc. But you can also sort an array on the dates in it.
array.sort((a,b) => new Date(b.date) - new Date(a.date));
You can nsort an array with numbers, letters, strings etc. But you can also sort an array on the dates in it.
array.sort((a,b) => new Date(b.date) - new Date(a.date));
Sort an array case insensitive
When sorting an array where strings are present starting with a
capital letter and strings without a capital letter then the
strings starting with a capital letter will get first.
var names = ['C', 'javascript', 'Java', "python",'Lua', 'basic'];
names.sort()
alert(names)
The alert will show: C,Java,Lua,basic,javascript,python
Obviously that is not what we want. We want the array to be in
alphabetical order. Use the next piece of code for achieving this.
var names = ['C', 'javascript', 'Java', "python",'Lua', 'basic'];
names.sort(function (a, b) {
var a = a.toUpperCase();
var b = b.toUpperCase();
return (a === b) ? 0 : a > b ? 1 : -1;
});
alert(names);
When sorting an array where strings are present starting with a
capital letter and strings without a capital letter then the
strings starting with a capital letter will get first.
var names = ['C', 'javascript', 'Java', "python",'Lua', 'basic'];
names.sort()
alert(names)
The alert will show: C,Java,Lua,basic,javascript,python
Obviously that is not what we want. We want the array to be in
alphabetical order. Use the next piece of code for achieving this.
var names = ['C', 'javascript', 'Java', "python",'Lua', 'basic'];
names.sort(function (a, b) {
var a = a.toUpperCase();
var b = b.toUpperCase();
return (a === b) ? 0 : a > b ? 1 : -1;
});
alert(names);
Sort an array with numbers
I presume this tip is well known, however I did not want to leave it out.
To sort an array the sort() command is used. Unfortunately it does not sort arrays with numbers well.
[0, 11, 5, 25, 2, 125, 3].sort();
This gains : [ 0, 11, 125, 2, 25, 3, 5]
The sort command sorts alphabetically not numeric.
The solution is to use a function with a comperator in the sort command.
var numberarray =[0, 11, 5, 25, 2, 125, 3];
numberarray.sort(function(a,b) {return a-b});
alert (numberarray);
This time it sorts like we want: [ 0, 2, 3, 5, 11, 25, 125 ]
I presume this tip is well known, however I did not want to leave it out.
To sort an array the sort() command is used. Unfortunately it does not sort arrays with numbers well.
[0, 11, 5, 25, 2, 125, 3].sort();
This gains : [ 0, 11, 125, 2, 25, 3, 5]
The sort command sorts alphabetically not numeric.
The solution is to use a function with a comperator in the sort command.
var numberarray =[0, 11, 5, 25, 2, 125, 3];
numberarray.sort(function(a,b) {return a-b});
alert (numberarray);
This time it sorts like we want: [ 0, 2, 3, 5, 11, 25, 125 ]
Sort an array descending
To sort an array we normally use the compare function (a-b).
To sort an array decending we only have to change this in (b-a).
var numbers = [ 1, 6, 4, 8, 5, 2];
numbers.sort(function(a,b) {return b-a});
alert (numbers);
To sort an array we normally use the compare function (a-b).
To sort an array decending we only have to change this in (b-a).
var numbers = [ 1, 6, 4, 8, 5, 2];
numbers.sort(function(a,b) {return b-a});
alert (numbers);
Sorting an array while creating a new array
When we sort an array with the array.sort method they array itself is sorted and there is not a new array created. Now suppose we want the array in its original form and a we want a sorted version.
As you will now arrays are Objects in Javascript. So if we duplicate an array it is not a new array but a reference to the original one. For example:
var proglangs = ['Python','Javascript','C++','Lua'];
var sortproglangs = proglangs;
sortproglangs = sortproglangs.sort();
alert(proglangs);
alert(sortproglangs);
sortproglangs.push("Basic");
alert(proglangs);
alert(sortproglangs);
As you can see adding 1 element to one of the arrays adds the element also to its copy.
If we do not want this to happen we have to make sure that the copy is indeed a new array. This can be done with slice()
var proglangs = ['Python','Javascript','C++','Lua'];
var sortproglangs = proglangs.slice();
sortproglangs = sortproglangs.sort();
alert(proglangs);
alert(sortproglangs);
proglangs.push("Basic");
alert("proglangs after adding : "+proglangs);
alert("sortproglangs after adding : "+sortproglangs);
When we sort an array with the array.sort method they array itself is sorted and there is not a new array created. Now suppose we want the array in its original form and a we want a sorted version.
As you will now arrays are Objects in Javascript. So if we duplicate an array it is not a new array but a reference to the original one. For example:
var proglangs = ['Python','Javascript','C++','Lua'];
var sortproglangs = proglangs;
sortproglangs = sortproglangs.sort();
alert(proglangs);
alert(sortproglangs);
sortproglangs.push("Basic");
alert(proglangs);
alert(sortproglangs);
As you can see adding 1 element to one of the arrays adds the element also to its copy.
If we do not want this to happen we have to make sure that the copy is indeed a new array. This can be done with slice()
var proglangs = ['Python','Javascript','C++','Lua'];
var sortproglangs = proglangs.slice();
sortproglangs = sortproglangs.sort();
alert(proglangs);
alert(sortproglangs);
proglangs.push("Basic");
alert("proglangs after adding : "+proglangs);
alert("sortproglangs after adding : "+sortproglangs);
Sorting an array while creating a new array with JSON
This is a variation on the previous tip. Again we want to sort an array resulting in a new array and at the same time keeping the original.
var proglang = ['Python','Javascript','C++','Lua'];
var sortproglang = JSON.parse(JSON.stringify(proglang));
sortproglang = sortproglang.sort();
alert(proglang);
alert(sortproglang);
In this version the original array is converted to a JSON string from which a new array is made. The new array is then no longer just a reference to the old one.
This is a variation on the previous tip. Again we want to sort an array resulting in a new array and at the same time keeping the original.
var proglang = ['Python','Javascript','C++','Lua'];
var sortproglang = JSON.parse(JSON.stringify(proglang));
sortproglang = sortproglang.sort();
alert(proglang);
alert(sortproglang);
In this version the original array is converted to a JSON string from which a new array is made. The new array is then no longer just a reference to the old one.
Sort an array such that odd numbers occur first
If you need to sort an array in such a way that the odd numbers are placed in the front indexes this is how to achieve this:
var array=[314,1,2,3,575,4,5,6]
array.sort((a,b)=>{
if (a%2==b%2) return a-b;
if (a%2>b%2) return -1;
return 1;
})
console.log(array)
If you need to sort an array in such a way that the odd numbers are placed in the front indexes this is how to achieve this:
var array=[314,1,2,3,575,4,5,6]
array.sort((a,b)=>{
if (a%2==b%2) return a-b;
if (a%2>b%2) return -1;
return 1;
})
console.log(array)
Sort an array that includes subarrays
In your program there is an array filled with subarrays that contain the temperatuer per month. If you want to sort that array based on temperature value this is the method to do that.
var temperatures =
[
["Jan", 5],
["Feb", 7],
["Jul", 25],
["Aug", 23],
["Okt", 18]
];
temperatures.sort(function(a,b) {return a[1]-b[1]});
console.log(temperatures);
The result will be:
[
[ 'Jan', 5 ],
[ 'Feb', 7 ],
[ 'Okt', 18 ],
[ 'Aug', 23 ],
[ 'Jul', 25 ]
]
In your program there is an array filled with subarrays that contain the temperatuer per month. If you want to sort that array based on temperature value this is the method to do that.
var temperatures =
[
["Jan", 5],
["Feb", 7],
["Jul", 25],
["Aug", 23],
["Okt", 18]
];
temperatures.sort(function(a,b) {return a[1]-b[1]});
console.log(temperatures);
The result will be:
[
[ 'Jan', 5 ],
[ 'Feb', 7 ],
[ 'Okt', 18 ],
[ 'Aug', 23 ],
[ 'Jul', 25 ]
]
Sort an array with objects on a property
Using array.sort(function (a,b){}) gives us the ability to sort an array alphabetically. However this is not possible if the array is filled with objects. The next snippet shows how to sort an array with objects on one of the objects properties.
var temps = [
{id: 1, month: "jan", rain: 0},
{id: 2, month: "feb", rain: 2},
{id: 3, month: "mrt", rain: 8},
{id: 4, month: "apr", rain: 6},
{id: 5, month: "may", rain: 10},
{id: 6, month: "jun", rain: 5},
]
function compare(a, b)
{
var rain1 = a.rain;
var rain2 = b.rain;
var comp = 0;
if (rain1 > rain2) {
comp = 1;
} else if (rain1 < rain2) {
comp = -1;
}
return comp;
}
temps.sort(compare)
document.write(JSON.stringify(temps))
In this example the array is sorted o the property rain. Changing a.rain and b.rain in a.month and b.month the array will alphabetically be sorted on the property month. If we use a.id and b.id the array will get sorted on the property id.
If you like arrow functions then you can replace the above function with the next line:
temps.sort((a,b) => (a.rain > b.rain) ? 1 : ((b.rain > a.rain) ? -1 : 0));
Using array.sort(function (a,b){}) gives us the ability to sort an array alphabetically. However this is not possible if the array is filled with objects. The next snippet shows how to sort an array with objects on one of the objects properties.
var temps = [
{id: 1, month: "jan", rain: 0},
{id: 2, month: "feb", rain: 2},
{id: 3, month: "mrt", rain: 8},
{id: 4, month: "apr", rain: 6},
{id: 5, month: "may", rain: 10},
{id: 6, month: "jun", rain: 5},
]
function compare(a, b)
{
var rain1 = a.rain;
var rain2 = b.rain;
var comp = 0;
if (rain1 > rain2) {
comp = 1;
} else if (rain1 < rain2) {
comp = -1;
}
return comp;
}
temps.sort(compare)
document.write(JSON.stringify(temps))
In this example the array is sorted o the property rain. Changing a.rain and b.rain in a.month and b.month the array will alphabetically be sorted on the property month. If we use a.id and b.id the array will get sorted on the property id.
If you like arrow functions then you can replace the above function with the next line:
temps.sort((a,b) => (a.rain > b.rain) ? 1 : ((b.rain > a.rain) ? -1 : 0));
Sort an array depending on values of another array
This sounds cryptic and needs some explanation.
Suppose yoo have an array with sorted elements. And there is another array with the elements mixed up. You want to sort the mixed up array in the same manner as the sorted array. Here is an example that shows how you can do that.
var all = ["Basic", "C++", "Javascript", "Lua", "Python"]
var test = ["Javascript", "Basic"]
test.sort(function(a,b){
return all.indexOf(a) - all.indexOf(b);
})
alert(test)
The alert will show: Basic,Javascript
You could use this to sort an array with mixed up months to the right order.
This sounds cryptic and needs some explanation.
Suppose yoo have an array with sorted elements. And there is another array with the elements mixed up. You want to sort the mixed up array in the same manner as the sorted array. Here is an example that shows how you can do that.
var all = ["Basic", "C++", "Javascript", "Lua", "Python"]
var test = ["Javascript", "Basic"]
test.sort(function(a,b){
return all.indexOf(a) - all.indexOf(b);
})
alert(test)
The alert will show: Basic,Javascript
You could use this to sort an array with mixed up months to the right order.
Sorting an array with words with accents
Foreign words often have accents. Sorting an array with these words will not succeed. To sort it the right way use localeCompare() in your sort function. here is an example.
var words = ["café", "rosé", "scène", "etagère", "être", "gêne"];
words.sort();
alert("Normal sort without using localeCompare : " + woorden);
words.sort(function(a, b){return a.localeCompare(b)});
alert("Sorting using localeCompare : " + words);
Foreign words often have accents. Sorting an array with these words will not succeed. To sort it the right way use localeCompare() in your sort function. here is an example.
var words = ["café", "rosé", "scène", "etagère", "être", "gêne"];
words.sort();
alert("Normal sort without using localeCompare : " + woorden);
words.sort(function(a, b){return a.localeCompare(b)});
alert("Sorting using localeCompare : " + words);
Split an array in half
If you need to split an array in half and put the contents in two new arrays, the next snippet shows how to do that.
var array = [1, 2, 3, 4, 5, 6]
var mid = Math.ceil(array.length / 2);
var firstpart = array.splice(0, mid)
var secondpart = array.splice(-mid)
alert(firstpart)
alert(secondpart)
If you need to split an array in half and put the contents in two new arrays, the next snippet shows how to do that.
var array = [1, 2, 3, 4, 5, 6]
var mid = Math.ceil(array.length / 2);
var firstpart = array.splice(0, mid)
var secondpart = array.splice(-mid)
alert(firstpart)
alert(secondpart)
Stack creation
If you are familiar with Machinelanguage programming you know there is a special kind of storage called a stack. A stack is build on Last-In-First-Out functionality. It is a kind of pile where you put things on top of eachtother and you can only take the top item away. We can easily build a stack with an array and then use the array.push() and array.pop commands.
var stack = [];
var vara;
function instack(data)
{
stack.push(data);
}
function fromstack()
{
return stack.pop();
}
Or even shorter with arrow functions:
instack=(data)=>stack.push(data);
fromstack=()=>stack.pop();
Two functions are created. The first has the name instack() and we use this to push data on the stack. The second has the name from.stack() and retrieves (and removes) the last element put on the stack. You can use them as follows:
instack(10);
instack(5);
alert(stack);
vara = fromstack();
alert(vara);
If you are familiar with Machinelanguage programming you know there is a special kind of storage called a stack. A stack is build on Last-In-First-Out functionality. It is a kind of pile where you put things on top of eachtother and you can only take the top item away. We can easily build a stack with an array and then use the array.push() and array.pop commands.
var stack = [];
var vara;
function instack(data)
{
stack.push(data);
}
function fromstack()
{
return stack.pop();
}
Or even shorter with arrow functions:
instack=(data)=>stack.push(data);
fromstack=()=>stack.pop();
Two functions are created. The first has the name instack() and we use this to push data on the stack. The second has the name from.stack() and retrieves (and removes) the last element put on the stack. You can use them as follows:
instack(10);
instack(5);
alert(stack);
vara = fromstack();
alert(vara);
Sum the figures in an array
Suppose you have an array that contains the order of a customer. Alternating the elements contain a name and the price. To add all prices you can use the next example.
var order = ["ESP32 Simplified", 19.95, 'Javascript tips', 19.95];
var total = 0;
for(var i = 0; i < order.length; i++)
{
var price = order[i];
if(+price)
{
total += +price;
};
};
console.log(total);
Suppose you have an array that contains the order of a customer. Alternating the elements contain a name and the price. To add all prices you can use the next example.
var order = ["ESP32 Simplified", 19.95, 'Javascript tips', 19.95];
var total = 0;
for(var i = 0; i < order.length; i++)
{
var price = order[i];
if(+price)
{
total += +price;
};
};
console.log(total);
Test if a value occurs in an array
With array.includes() it is easy to test if a value or text occurs in the array.
var languages = ["Javascript", "Lua", "Python"]
var testlang = languages.includes("Basic")
alert(testlang)
The alert will show "false"
With array.includes() it is easy to test if a value or text occurs in the array.
var languages = ["Javascript", "Lua", "Python"]
var testlang = languages.includes("Basic")
alert(testlang)
The alert will show "false"
Test if a value occurs in an array 2
We can test if a value or text occurs in an array with a clkever use of array.indexOf(). Here is how to perform the test.
var languages = ["Javascript", "Lua", "Python"]
if(languages.indexOf("Basic") == -1)
{
alert("The language Basic is not present")
}
array.indexOf(variabele) will give the index if the variabele is present and otherwise it will give -1.
We can test if a value or text occurs in an array with a clkever use of array.indexOf(). Here is how to perform the test.
var languages = ["Javascript", "Lua", "Python"]
if(languages.indexOf("Basic") == -1)
{
alert("The language Basic is not present")
}
array.indexOf(variabele) will give the index if the variabele is present and otherwise it will give -1.
Test if an array has empty elements
to test if an arry has empty elements we can use myArray.every(element => element !== "") You can replace the "" by any other string or element you wnat to search for. The next snippet gives an example on how you can use this.
testarray = ["a", "b", "", "d"]
if (testarray.every(element => element !== ""))
{
alert ("no empty elements");
}
else
{
alert("found some empty elements");
}
to test if an arry has empty elements we can use myArray.every(element => element !== "") You can replace the "" by any other string or element you wnat to search for. The next snippet gives an example on how you can use this.
testarray = ["a", "b", "", "d"]
if (testarray.every(element => element !== ""))
{
alert ("no empty elements");
}
else
{
alert("found some empty elements");
}
Test if an array is empty
You might define an array at the strat of your program but not fill it with ietems. The next lines of code show how to test if the array is (still) empty
array = []
if (typeof array !== 'undefined' && array.length === 0)
{
alert("no elements in array")
}
You might define an array at the strat of your program but not fill it with ietems. The next lines of code show how to test if the array is (still) empty
array = []
if (typeof array !== 'undefined' && array.length === 0)
{
alert("no elements in array")
}
Test if an element exists and give the next one in line
Suppose there is a line of courses in programming languages you need to follow. When you finished a course you need to do the next. The languages are array elements. The finished course is a variable. The following function supplies the next course you must follow.
var languages = ["Basic", "Python", "Javascript", "C++"];
function nextcourse(lookfor,languages)
{
found = languages.indexOf(lookfor) + 1;
return languages[found] || "All done";
}
document.write(nextcourse('Javascript', languages));
document.write("<br>");
document.write(nextcourse('Lua', languages));
If the variable contains a language which is not in the list (like Lua) then the array index will be -1 and the function takes the first index being Basic. When all courses have been taken and the variable contains C++ then the value of found will become 4. This is a non-existent index and the || will be chosen which displays "All Done"
Suppose there is a line of courses in programming languages you need to follow. When you finished a course you need to do the next. The languages are array elements. The finished course is a variable. The following function supplies the next course you must follow.
var languages = ["Basic", "Python", "Javascript", "C++"];
function nextcourse(lookfor,languages)
{
found = languages.indexOf(lookfor) + 1;
return languages[found] || "All done";
}
document.write(nextcourse('Javascript', languages));
document.write("<br>");
document.write(nextcourse('Lua', languages));
If the variable contains a language which is not in the list (like Lua) then the array index will be -1 and the function takes the first index being Basic. When all courses have been taken and the variable contains C++ then the value of found will become 4. This is a non-existent index and the || will be chosen which displays "All Done"
Test wether a variable is present in a flat array
If we just need a quick check wether a variable is present in a flat array we can use the next arrow-function:
testarray = ["a", "b", "c", "d"];
isinarray =(value) => testarray.includes(value);
testvar = "b";
alert(isinarray(testvar));
Here we test for the value "b" and the alert will say true.
If we just need a quick check wether a variable is present in a flat array we can use the next arrow-function:
testarray = ["a", "b", "c", "d"];
isinarray =(value) => testarray.includes(value);
testvar = "b";
alert(isinarray(testvar));
Here we test for the value "b" and the alert will say true.
Test if two array's are equal
To test wether two arrays are equal convert them first to strings
and then test for equality like the next sample shows.
var first = [1, 2, 3, 4, 5];
var second = [1, 2, 3, 4, 5];
var equal = first.toString() === second.toString();
alert(gelijk);
To test wether two arrays are equal convert them first to strings
and then test for equality like the next sample shows.
var first = [1, 2, 3, 4, 5];
var second = [1, 2, 3, 4, 5];
var equal = first.toString() === second.toString();
alert(gelijk);
Test if two array's are equal 2
To test wether two arrays are equal it is not possivble to use (first == second). Both arrays point to different memory locations. Next to that == does not test nested (multidimensional) arrays. Another methode as the one mentioned in the previous tip is to use JSON.stringify like the next snippet shows.
var first = [1, 2, 3, 4, 5, ["a", "b"]];
var second = [1, 2, 3, 4, 5, ["a", "b"]];
alert(JSON.stringify(first)==JSON.stringify(second));
To test wether two arrays are equal it is not possivble to use (first == second). Both arrays point to different memory locations. Next to that == does not test nested (multidimensional) arrays. Another methode as the one mentioned in the previous tip is to use JSON.stringify like the next snippet shows.
var first = [1, 2, 3, 4, 5, ["a", "b"]];
var second = [1, 2, 3, 4, 5, ["a", "b"]];
alert(JSON.stringify(first)==JSON.stringify(second));
Test if two arrays contain the same elements
The previous tip tested wether the arrays were equal. By sorting
the elements we can test if the array elements are equal.
var first = [1, 2, 3, 4, 5];
var second = [1, 2, 3, 4, 5];
var equal = first.toString().sort === second.toString().sort;
alert(gelijk);
The previous tip tested wether the arrays were equal. By sorting
the elements we can test if the array elements are equal.
var first = [1, 2, 3, 4, 5];
var second = [1, 2, 3, 4, 5];
var equal = first.toString().sort === second.toString().sort;
alert(gelijk);
Test wether an array contains the elements of another array
The next snippet shows a fast way to test wether all the elements of an array
are present in another array.
var array1 = ["C++", "Java", "Javascript", "Lua", "Python"];
var array2 = ["Javascript", "Lua", "Python"];
var present = array2.every((item) => array1.includes(item));
alert(present)
The next snippet shows a fast way to test wether all the elements of an array
are present in another array.
var array1 = ["C++", "Java", "Javascript", "Lua", "Python"];
var array2 = ["Javascript", "Lua", "Python"];
var present = array2.every((item) => array1.includes(item));
alert(present)
Test wether an array contains the elements of another array 2
Here is another method to search if the elements of an array exist in another array. The difference is that the original array is two dimensional.
var micros = [["Arduino", "ESP8266"], ["ESP8266", "ESP32"], ["Arduino","Raspberry Pico"]];
function search(gezocht, micros) {
return !!micros.find(micros => micros.join() === gezocht.join());
}
alert(search(["Arduino","ESP32"], micros)); // false
alert(search(["ESP8266", "ESP32"], micros)); // true
Here is another method to search if the elements of an array exist in another array. The difference is that the original array is two dimensional.
var micros = [["Arduino", "ESP8266"], ["ESP8266", "ESP32"], ["Arduino","Raspberry Pico"]];
function search(gezocht, micros) {
return !!micros.find(micros => micros.join() === gezocht.join());
}
alert(search(["Arduino","ESP32"], micros)); // false
alert(search(["ESP8266", "ESP32"], micros)); // true
Three methods to iterate over an array with a for loop
There are 3 ways to iterate over an array with a for loop to look for a certain value or change values. Here is an example that uses all three to get the same result.
var testarray = [3, 5, 7, 9, 11];
for (i=0; i<testarray.length; i++)
{
if (testarray[i] == 7)
{
console.log("found");
}
}
for (var index in testarray)
{
if (testarray[index] == 7)
{
console.log("found");
}
}
for (var element of testarray)
{
if (element == 7)
{
console.log("found");
}
}
The first for loop is the traditional method in which we determine the length of the array and use that to walk through all its elements to find the value 7.
The second for loop uses the word "in" to automatically determine the length and uses the variable index to walk through the elements.
The third loop uses "of" to walk through the elements. The length is automatically detected and the index value is not used. The for-of combination walks automatically through all elements.
Which one to use depends on the purpose of the loop and your personal preferences.
There are 3 ways to iterate over an array with a for loop to look for a certain value or change values. Here is an example that uses all three to get the same result.
var testarray = [3, 5, 7, 9, 11];
for (i=0; i<testarray.length; i++)
{
if (testarray[i] == 7)
{
console.log("found");
}
}
for (var index in testarray)
{
if (testarray[index] == 7)
{
console.log("found");
}
}
for (var element of testarray)
{
if (element == 7)
{
console.log("found");
}
}
The first for loop is the traditional method in which we determine the length of the array and use that to walk through all its elements to find the value 7.
The second for loop uses the word "in" to automatically determine the length and uses the variable index to walk through the elements.
The third loop uses "of" to walk through the elements. The length is automatically detected and the index value is not used. The for-of combination walks automatically through all elements.
Which one to use depends on the purpose of the loop and your personal preferences.
Universal array sorter
In the tip where I showed how to sort an array with words that have accents there is one problem. That function will not sort numbers. So here is a universal array sort routine that sorts strings, strings with accents and numbers.
var figures = [3, 10, 2, 14, 7, 2, 9, 5];
var words = ["café", "rosé", "scène", "etagère", "être", "gêne"];
function sortall(a, b)
{
if (a < b)
{
return -1;
}
else if (a > b)
{
return 1;
} else
{
return 0;
}
}
figures.sort(sortall);
words.sort(sortall);
alert(figures);
alert(words);
In the tip where I showed how to sort an array with words that have accents there is one problem. That function will not sort numbers. So here is a universal array sort routine that sorts strings, strings with accents and numbers.
var figures = [3, 10, 2, 14, 7, 2, 9, 5];
var words = ["café", "rosé", "scène", "etagère", "être", "gêne"];
function sortall(a, b)
{
if (a < b)
{
return -1;
}
else if (a > b)
{
return 1;
} else
{
return 0;
}
}
figures.sort(sortall);
words.sort(sortall);
alert(figures);
alert(words);
Use an array to store your functions.
An array is ideal to store large amounts of data like numbers, strings and objects. A not well known fact is that you can also store functions in an array. By calling the array element the function will be executed. This could be used instead of thw switch command. Here is an example.
var a=5;
var b=6;
var array_of_functions = [
function() { c=a*b; return c },
function() { alert('a string') },
function() { alert('a string') },
function() { alert('a string') }
]
d=array_of_functions[0]();
alert(d);
array_of_functions[1]();
alert(d) Will show 30 as the answer as the function in array_of_functions[0] is executed. Do not forget to place parentheses () at the end of the call otherwise the function will not be executed.
An array is ideal to store large amounts of data like numbers, strings and objects. A not well known fact is that you can also store functions in an array. By calling the array element the function will be executed. This could be used instead of thw switch command. Here is an example.
var a=5;
var b=6;
var array_of_functions = [
function() { c=a*b; return c },
function() { alert('a string') },
function() { alert('a string') },
function() { alert('a string') }
]
d=array_of_functions[0]();
alert(d);
array_of_functions[1]();
alert(d) Will show 30 as the answer as the function in array_of_functions[0] is executed. Do not forget to place parentheses () at the end of the call otherwise the function will not be executed.
Using text as array index
When an array is defined the elements get an index number starting at 0. This gives us the elements array[0], arra[1], array[2] etc. etc. Few programmers are aware that we can give the array elements a name. The next example creates an array called "languages" and uses the name of a programming language as the index. At fist every element contains the value no. Next we change the value of the element with index "javascript" to yes.
var languages = [];
languages["python"]="no";
languages["javascript"]="no";
languages["C++"]="o";
alert(languages["javascript"])
languages["javascript"]="yes";
alert(languages["javascript"])
We can use this array as any other array. The problem is that we can not iterate over the array or use array methods. The next commands will therefore not work.
alert("The array contains "+languages);
alert(languages.length);
alert(languages.indexOf("javascript"));
When an array is defined the elements get an index number starting at 0. This gives us the elements array[0], arra[1], array[2] etc. etc. Few programmers are aware that we can give the array elements a name. The next example creates an array called "languages" and uses the name of a programming language as the index. At fist every element contains the value no. Next we change the value of the element with index "javascript" to yes.
var languages = [];
languages["python"]="no";
languages["javascript"]="no";
languages["C++"]="o";
alert(languages["javascript"])
languages["javascript"]="yes";
alert(languages["javascript"])
We can use this array as any other array. The problem is that we can not iterate over the array or use array methods. The next commands will therefore not work.
alert("The array contains "+languages);
alert(languages.length);
alert(languages.indexOf("javascript"));
Using the array map method
The map function is used to alter all elements in an array with a single function. There are several ways to using map which are listed below. Use the one which is most easy/clear.
Method 1.
array=[1,2,3];
array=array.map(x => x * 2);
alert(array);
Method 2.
array=[1,2,3];
array = array.map(function (x) { return x * 2 })
alert(array);
Method 3.
array=[1,2,3];
function double(x) { return x * 2 }
array = array.map(double)
alert(array);
Method 4.
array=[1,2,3];
const double = x => x * 2;
array = array.map(double)
alert(array);
The map function is used to alter all elements in an array with a single function. There are several ways to using map which are listed below. Use the one which is most easy/clear.
Method 1.
array=[1,2,3];
array=array.map(x => x * 2);
alert(array);
Method 2.
array=[1,2,3];
array = array.map(function (x) { return x * 2 })
alert(array);
Method 3.
array=[1,2,3];
function double(x) { return x * 2 }
array = array.map(double)
alert(array);
Method 4.
array=[1,2,3];
const double = x => x * 2;
array = array.map(double)
alert(array);
Walk through all array elements
Using the array.foreach() method we can easily walk through an entire array.
var languages=["C++","Javascript","Python"];
languages.forEach
(
function f(i)
{
console.log(i);
}
)
Using the array.foreach() method we can easily walk through an entire array.
var languages=["C++","Javascript","Python"];
languages.forEach
(
function f(i)
{
console.log(i);
}
)
Walk through an associative array
You can walk through an array by adressing the index numbers or using forEach(). However that will not work if your array is associative.
var learned=[]
learned["Basic"]="yes"
learned["C++"]="yes"
learned["Fortran"]="no"
learned.forEach(element => console.log(element));
The forEach command will not find any array elements.
To loop through an associative arry you can use the next code.
var learned=[]
learned["Basic"]="yes"
learned["C++"]="yes"
learned["Fortran"]="no"
for (var element in learned) {
var yesorno = learned[element];
console.log(element, yesorno);
}
What is the largest number in an array
To find the largest number in an array you could iterate through the array with a for-loop. It is however shorter to use the math.max function. This function normally does not operate on an array but using the spread operator it works flawlessly.
var numbers = [2, 5, 3, 9, 7, 6]
maximum = Math.max(...numbers);
alert(maximum);
To find the largest number in an array you could iterate through the array with a for-loop. It is however shorter to use the math.max function. This function normally does not operate on an array but using the spread operator it works flawlessly.
var numbers = [2, 5, 3, 9, 7, 6]
maximum = Math.max(...numbers);
alert(maximum);
What is the second largest number in an array
To find the second largest number in an array start with finding the largest number. Remove that number and then search again for the largest number. Here is how to do that.
var array = [ 20, 15, 35, 80, 45];
var max = Math.max(...array);
array.splice(array.indexOf(max),1);
max2 = Math.max(...array);
alert(max2)
What is the smallest number in an array
To find the smallest number in an array you could iterate through the array with a for-loop. It is however shorter to use the math.min function. This function normally does not operate on an array but using the spread operator it works flawlessly.
var numbers = [2, 5, 3, 9, 7, 6]
maximum = Math.min(...numbers);
alert(maximum);
To find the smallest number in an array you could iterate through the array with a for-loop. It is however shorter to use the math.min function. This function normally does not operate on an array but using the spread operator it works flawlessly.
var numbers = [2, 5, 3, 9, 7, 6]
maximum = Math.min(...numbers);
alert(maximum);
Where to find the lowets and highest values in an array
In a previous tip in this chapter is shown how to find what the lowest and highest numbers in an array are. But where are they located.
var numbers = [1, 2, 1.5, 6.7];
var max = Math.max(...numbers);
var min = Math.min(...numbers);
alert(nummers.indexOf(min);
alert(nummers.indexOf(max);
The alerts will show respectively the place in the array where min and max are located. This only works with arrays with numbers.
In a previous tip in this chapter is shown how to find what the lowest and highest numbers in an array are. But where are they located.
var numbers = [1, 2, 1.5, 6.7];
var max = Math.max(...numbers);
var min = Math.min(...numbers);
alert(nummers.indexOf(min);
alert(nummers.indexOf(max);
The alerts will show respectively the place in the array where min and max are located. This only works with arrays with numbers.