Data Structures and Algorithms
muigai unaka
Week 2
Collection | Index/Access | Search/Find | Insert | Delete |
---|---|---|---|---|
Array | O(1) Constant | O(N) Linear | O(N) Linear | O(N) Linear |
Set | O(1) Constant |
O(N) Linear |
O(N) Linear | O(N) Linear |
Map | O(1) Constant | O(N) Linear |
O(1) Constant |
O(1) Constant |
Object | O(1) Constant | O(N) Linear |
O(1) Constant |
O(1) Constant |
Time Complexity of Collections
Array
Add / Remove from Array
.push(elem) adds an element to the end
.shift() gets the first element from the array, causing the 2nd element to become the 1st
.pop() gets the last element from the array and returns it
.unshift(elem) adds an element to the beginning of the array
.splice(pos, deleteCount, ...items) – at index pos delete deleteCount elements and insert items
Method | Definition | Performance |
---|---|---|
.push(elem) | adds an element to the end | O(1) |
.shift() | gets the first element from the array, causing the 2nd element to become the 1st | O(N) |
.pop() | gets the last element from the array and returns it | O(1) |
.unshift(elem) | adds an element to the beginning of the array | O(N) |
.splice(pos, delAmt, ...items) | at index pos delete delAmt elements and insert items | O(N) |
Add / Remove from Array
Search Array
.indexOf(item)/.lastIndexOf(item, pos) – look for item starting from position pos, return the index or -1 if not found.
.includes(value) – returns true if the array has value, otherwise false.
.find(func)/filter(func) – filter elements through the function, return first/all values that make it return true.
.findIndex(func) is like find, but returns the index instead of a value.
Method | Definition | Performance |
---|---|---|
.indexOf(item, pos) | search for item, left to right, from index pos, return the index or -1 if not found. | O(N) |
.lastIndexOf(item, pos) | search for item, right to left, from index pos, return the index or -1 if not found. | O(N) |
.includes(val) | returns true if the array has value val, otherwise false | O(N) |
.find(func) or .filter(func) | filter elements through the function, return first/all values that meet the condition state | O(N) |
.findIndex(func) | similar to find, but returns the index instead of a value. | O(N) |
Search Array
// Multidimensional arrays
// Arrays can have items that are also arrays.
// We can use it for multidimensional arrays,
// for example to store matrices:
let matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
console.log( matrix[1][1] ); // 5, the central element
Multidimensional Array or "Matrix"
The map() method takes in a function and is called on an array. It creates a new array with each element in the array mutated by the provided function.
.map()
.map()
let arr = [5, 7, 4, 12];
arr.map(function(currentValue, idx, copyOfArr) {
console.log(currentValue);
console.log(idx);
console.log(copyOfArr);
console.log(currentValue * 7)
return currentValue * 7
});
console.log(arrMultipliedBy7);
// output: [ 35, 49, 28, 84 ]
The filter() method takes in a function and is called on an array. It creates a new array after checking the given function's condition against each element in the array
.filter()
let cars = [
'Mclaren','Lamborghini','Ferrari','Porsche','Mercedes','Corvette'
];
let filteredCars = cars.filter(function(car, idx, copyOfCars) {
console.log(car);
console.log(idx);
console.log(copyOfCars);
console.log(car.length > 7); // condition to filter by
return car.length > 7
});
console.log(filteredCars);
// output: [ "Lamborghini", "Mercedes", "Corvette" ]
.filter()
The reduce() method takes in a function and is called on an array. It creates a new array after checking the given function's condition against each element in the array
.reduce()
const nums = [3, 4, 2, 9];
const reduce = function (accumulator, currentValue, idx, copyOfNums) {
console.log(accumulator)
console.log(currentValue)
console.log(idx)
console.log(copyOfNumbers)
return accumulator + currentValue;
};
console.log(nums.reduce(reduce)); // output: 18
console.log(nums.reduce(reduce, 7)); // output: 25
.reduce()
Array.isArray(arr)
Set
Methods on Set
.add(val) – adds a value val, returns the set itself.
.delete(val) – removes the value val, returns true if value existed at the moment of the call, otherwise false
.has(val) – returns true if the value val exists in the set, otherwise false
.size – is the elements count in the set
Method | Definition | Performance |
---|---|---|
.add(val) | adds a value val, returns the set itself. | O(N) |
.delete(val) | removes the value val, returns true if value existed at the moment of the call, otherwise false | O(N) |
.has(val) | returns true if the value val exists in the set, otherwise false | O(N) |
.size | is the elements count in the set | O(1) |
Methods on Set
Object
Interacting with Object
let aubrey = { lname: "Ever", fname: "Greatest" };
aubrey["lname"] - use bracket notation to get/set a value of an object
aubrey.fname - use dot notation to get/set a value of an object
delete aubrey.fname - use the delete operator to remove a property/value pair from an object
Object.keys(obj) – returns an array of keys
Object.values(obj) – returns an array of values
Object.entries(obj) – returns an array of [key, value] pairs
Deep Clone Object
const deepClone = (source) => {
// If the source isn't an Object or Array, throw an error.
if ( !(source instanceof Object) || source instanceof Date || source instanceof String ) {
throw 'Only Objects or Arrays are supported.'
}
// Set the target data type before copying.
let target = Array.isArray(source) ? [] : {};
for (let prop in source){
// Make sure the property isn't on the protoype
if ( source instanceof Object && !(source instanceof Array)
&& !(source.hasOwnProperty(prop)) ) {
continue;
}
// If the current property is an Array or Object,
// recursively clone it, else copy it's value
if ( source[prop] instanceof Object && !(source[prop] instanceof Date)
&& !(source[prop] instanceof String) ) {
target[prop] = deepClone(source[prop])
} else {
target[prop] = source[prop]
}
}
return target;
}
Map
Methods on Map
.set(key, val) – stores the value val by the key.
.get(key) – returns the value by the key, undefined if key doesn’t exist in map.
.has(key) – returns true if the key exists, false otherwise.
.delete(key) – removes the value by the key
.size – returns the current element count.
Method | Definition | Performance |
---|---|---|
.set(key, val) | stores the value val by the key. | O(1) |
.get(key) | returns the value by the key, undefined if key doesn’t exist in map | O(1) |
.has(key) | returns true if the key exists, false otherwise | O(N) |
.delete(key) | removes the value by the key |
O(N) |
.size | returns the current element count. | O(1) |
Methods on Map
Maswali?
Data Structures and Algorithms Week 2
By Muigai Unaka
Data Structures and Algorithms Week 2
Data Structures and Algorithms week 2 at Resilient Coders. Part 2 of JavaScript refresher
- 425