array manipulation js code example
Example 1: array methods in javascript
<script>
function getUnique(array){
var uniqueArray = [];
for(var value of array){
if(uniqueArray.indexOf(value) === -1){
uniqueArray.push(value);
}
}
return uniqueArray;
}
var names = ["John", "Peter", "Clark", "Harry", "John", "Alice"];
var uniqueNames = getUnique(names);
console.log(uniqueNames);
</script>
Example 2: modify array js
let newArray = oldArray.map(funcToEachElem);
Example 3: 6 ways to modify an array javascript
let browsers = ['chrome', 'firefox', 'edge'];
browsers.unshift('safari');
console.log(browsers);
let browsers = ['chrome', 'firefox', 'edge'];
browsers.push('safari');
console.log(browsers);
let browsers = ['chrome', 'firefox', 'edge'];
browsers.shift();
console.log(browsers);
let browsers = ['chrome', 'firefox', 'edge'];
browsers.pop();
console.log(browsers);
var fruits = ["Banana", "Orange", "Apple", "Mango"];
function myFunction() {
fruits.splice(3, 0, "Lemon", "Kiwi");
document.getElementById("demo").innerHTML = fruits;
}
var fruits = ["Banana", "Orange", "Apple", "Mango"];
function myFunction() {
fruits.splice(2, 1);
document.getElementById("demo").innerHTML = fruits;
}
Example 4: functions in arrays javascript
var argsContainer = ['hello', 'you', 'there'];
var functionsContainer = [];
for (var i = 0; i < argsContainer.length; i++) {
var currentArg = argsContainer[i];
functionsContainer.push(function(currentArg){
console.log(currentArg);
});
};
for (var i = 0; i < functionsContainer.length; i++) {
functionsContainer[i](argsContainer[i]);
}