useful inbuilt function mostly used in objects and array
const person = {
name: "John",
age: 30,
address: {
street: "123 Main St",
city: "Exampleville",
country: "Exampleland"
},
hobbies: ["reading", "coding", "running"],
sayHello: function() {
console.log("Hello, my name is " + this.name);
}
};
// access -> obj.key (0r) obj['key_name']
console.log(person.name); // Output: John
console.log(person.address.city); // Output: Exampleville
console.log(person['hobbies'][1]); // Output: coding
person.sayHello(); // Output: Hello, my name is John
// add / update value -> obj.key-name = value
person.isDeveloper = true
// delete -> key-value
delete person.isDeveloper
// Object.keys(obj) --> array of keys -> [k1,k2,k3]
const keys = Object.keys(person);
console.log(keys); // Output: ["name", "age", "address"]
// Object.values(obj) --> array of values -> [v1,v2,v3]
const values = Object.values(person);
console.log(values); // Output: ["John", 30, "123 Main St"]
// Object.entries(obj) --> array of both key and value ->[[k1,v1],[k2,v2]]
const entries = Object.entries(person);
console.log(entries); // Output: [["name", "John"], ["age", 30], ["address", "123 Main St"]]
// loop
// for in
for (let key in person) {
console.log(key + ": " + person[key]);
}
// forEach
Object.keys(person).forEach(key => {
console.log(key + ": " + person[key]);
});
Object.entries(person).forEach(([key, value]) => {
console.log(key + ": " + value);
});
const target = { name: "John" };
const source = { age: 30, address: "123 Main St" };
//Object.assign(dest,src) --> copy key:value src->dest
Object.assign(target, source);
console.log(target);
//spread operator
console.log({...target,...source});
// Output: { name: "John", age: 30, address: "123 Main St" }
//shallow copy
const originalObject = { name: "John", age: 30 };
// Using Object.assign()
const shallowCopy = Object.assign({}, originalObject);
// Using spread operator
const shallowCopy = { ...originalObject };
// deep copy
function deepCopyObject(obj) {
const copy = Array.isArray(obj) ? [] : {};
for (let key in obj) {
if (typeof obj[key] === "object" && obj[key] !== null) {
copy[key] = deepCopyObject(obj[key]);
} else {
copy[key] = obj[key];
}
}
return copy;
}
const originalObject = { name: "John", address: { city: "Exampleville" } };
const deepCopy = deepCopyObject(originalObject);
array
// shallow copy
const originalArray = [1, 2, 3, 4, 5];
// Using slice()
const shallowCopy = originalArray.slice();
// Using spread operator
const shallowCopy = [...originalArray];
// Using concat()
const shallowCopy = originalArray.concat();
// deep copy
const originalArray = [1, 2, [3, 4], { name: "John" }];
const deepCopy = JSON.parse(JSON.stringify(originalArray));
// loop
const numbers = [1, 2, 3, 4, 5];
// for loop -> index
for (let i = 0; i < numbers.length; i++) {
console.log(numbers[i]);
}
// forEach -> each value
numbers.forEach(function(number) {
console.log(number);
});
// for of -> each value
for (let number of numbers) {
console.log(number);
}
// map -> each value -> return new array
const squaredNumbers = numbers.map(function(number) {
return number * number;
});
console.log(squaredNumbers);
// filter -> each value -> return filtered new array
const evenNumbers = numbers.filter(function(number) {
return number % 2 === 0;
});
console.log(evenNumbers);
let arr = [1,2,3,4]
arr.push(2) --> [1,2,3,4,5] // add element to the last position
arr.pop() --> [1,2,3,4] // remove element from the last position
arr.unshift(5) --> [5,1,2,3,4] // add element to the first position
arr.shift() --> [1,2,3,4] // remove element from the first position
let arr = [1,2,3,4]
arr.slice(1) --> [2,3,4]
arr.slice(1,3) --> [2,3]
arr.slice(-1) --> [4]
let arr = [1,2,3,4]
// modify orginal array
splice(index,No of element to delete,element to add)
// arr.splice(1,1,'gokul','karthik') --> [1,'gokul','karthik',3,4]
// arr.splice(1,0,'gokul','karthik') --> [1,2,'gokul','karthik',3,4]
arr.splice(1,1) --> [1,3,4]
//every --> true if all element satisfy the condition
//some --> true if atleast 1 element satisfy the condition
// indexOf --> return index of 1st matched element
// lastIndexOf --> return index of last matched element
// indexOf and lastIndexOf
const arr = [1, 2, 3, 4, 2, 5];
console.log(arr.indexOf(2)); // Output: 1
console.log(arr.lastIndexOf(2)); // Output: 4
console.log(arr.indexOf(6)); // Output: -1
console.log(arr.lastIndexOf(6)); // Output: -1
// findIndex --> return index of 1st matched element
// findLastIndex --> return index of last matched element
// findIndex and findLastIndex
const users = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Jane' },
{ id: 3, name: 'Doe' },
{ id: 2, name: 'Alex' }
];
console.log(users.findIndex(user => user.id === 2)); // Output: 1
console.log(users.findLastIndex(user => user.id === 2)); // Output: 3
console.log(users.findIndex(user => user.id === 5)); // Output: -1
console.log(users.findLastIndex(user => user.id === 5)); // Output: -1
// find --> return 1st matched element
// findLast --> return last matched element
// find and findLast
const fruits = ['apple', 'banana', 'orange', 'banana', 'grapes'];
console.log(fruits.find(fruit => fruit === 'banana')); // Output: 'banana'
console.log(fruits.findLast(fruit => fruit === 'banana')); // Output: 'banana'
console.log(fruits.find(fruit => fruit === 'pineapple')); // Output: undefined
console.log(fruits.findLast(fruit => fruit === 'pineapple')); // Output: undefined
//sort
const strings = ['banana', 'apple', 'orange', 'grapes'];
//asc
const ascendingStrings = strings.slice().sort();
console.log(ascendingStrings); // Output: ["apple", "banana", "grapes", "orange"]
const ascendingStrings1 = strings.slice().sort((a, b) => a.localeCompare(b));
console.log(ascendingStrings1);
//dsc
const descendingStrings = strings.slice().sort((a, b) => b.localeCompare(a));
console.log(descendingStrings); // Output: ["orange", "grapes", "banana", "apple"]
const numbers = [5, 2, 9, 1, 8];
//asc
const ascendingNumbers = numbers.slice().sort((a, b) => a - b);
console.log(ascendingNumbers); // Output: [1, 2, 5, 8, 9]
//dsc
const descendingNumbers = numbers.slice().sort((a, b) => b - a);
console.log(descendingNumbers); // Output: [9, 8, 5, 2, 1]
const objects = [
{ name: 'John', age: 30 },
{ name: 'Jane', age: 25 },
{ name: 'Doe', age: 35 }
];
//asc
const ascendingObjects = objects.slice().sort((a, b) => a.age - b.age);
console.log(ascendingObjects);
// Output: [{ name: 'Jane', age: 25 }, { name: 'John', age: 30 }, { name: 'Doe', age: 35 }]
//dsc
const descendingObjects = objects.slice().sort((a, b) => b.age - a.age);
console.log(descendingObjects);
// Output: [{ name: 'Doe', age: 35 }, { name: 'John', age: 30 }, { name: 'Jane', age: 25 }]
// Array.of()
const arr = Array.of(1, 2, 3, 'four', true); // Creates an array with the provided arguments
console.log(arr); // Output: [1, 2, 3, 'four', true]
const emptyArr = Array.of(); // Creates an empty array
console.log(emptyArr); // Output: []
const singleElementArr = Array.of(5); // Creates an array with a single element
console.log(singleElementArr); // Output: [5]
// new Array()
const arr = new Array(1, 2, 3, 'four', true); // Creates an array with the provided arguments
console.log(arr); // Output: [1, 2, 3, 'four', true]
const emptyArr = new Array();
console.log(emptyArr); // Output: []
const singleElementArr = new Array(5);
console.log(singleElementArr); // Output: [ <5 empty items> ]
//arr.fill() --> modify original array
// Example 1: Filling an array with a static value
const arr = [1, 2, 3, 4, 5];
const filledArr = arr.fill(0); // Fill all elements with value 0
console.log(filledArr); // Output: [0, 0, 0, 0, 0]
// Example 2: Filling a subset of an array with a static value
const arr2 = [1, 2, 3, 4, 5];
const filledArr2 = arr2.fill(9, 1, 4); // Fill elements from index 1 (inclusive) to index 4 (exclusive) with value 9
console.log(filledArr2); // Output: [1, 9, 9, 9, 5]
// Example 3: Filling an empty array with a static value
const emptyArr = new Array(5); // Create an empty array with length 5
const filledEmptyArr = emptyArr.fill('default'); // Fill all elements with value 'default'
console.log(filledEmptyArr); // Output: ['default', 'default', 'default', 'default', 'default']
//Array.from()
const str = 'hello';
const arr = Array.from(str);
console.log(arr); // Output: ['h', 'e', 'l', 'l', 'o']
const set = new Set([1, 2, 3, 4, 5]);
const arrFromSet = Array.from(set);
console.log(arrFromSet); // Output: [1, 2, 3, 4, 5]
const nodeList = document.querySelectorAll('p');
const arrFromNodeList = Array.from(nodeList);
console.log(arrFromNodeList); // Output: Array of all <p> elements
//includes()
const array = [1, 2, 3, 4, 5];
console.log(array.includes(3)); // Output: true
console.log(array.includes(6)); // Output: false
// Example with fromIndex
console.log(array.includes(3, 2)); // Output: true (search from index 2)
console.log(array.includes(3, 4)); // Output: false (search from index 4)
//join() --> arr to string
const array = ['apple', 'banana', 'orange'];
const joinedString = array.join(); // Joins elements with comma separator by default
console.log(joinedString); // Output: "apple,banana,orange"
const joinedStringWithZero = array.join('0'); // Joins elements with "0" separator
console.log(joinedStringWithZero); // Output: "apple0banana0orange"
const joinedStringWithSpace = array.join(' '); // Joins elements with "0" separator
console.log(joinedStringWithSpace); // Output: "apple banana orange"
https://dev.to/codewithtee/15-array-methods-in-javascript-1p1m