Skip to main content

Data-structures

String

string.replaceAll()

  • Replace all instances of a string.
const s1 = "foo_bar_baz";
const s2 = s1.replaceAll('_', '-');

Array

array.at

  • The at() method is equivalent to the bracket notation when index is non-negative.
    • However, if provided a negative value it will index array from the back, just like python
const array1 = [5, 12, 8, 130, 44];

console.log(array1.at(0)) //5
console.log(array1.at(-1)) //44

array.toSorted()

  • Sort without mutating the original array.
const values = [1, 10, 21, 2];
const sortedValues = values.toSorted((a, b) => a - b);
console.log(sortedValues); // [1, 2, 10, 21]
console.log(values); // [1, 10, 21, 2]
  • String sorting
const fruits = ['Banana', 'Apple', 'Orange', 'Mango'];
const sortedNames = names.toSorted((a, b) => a.localeCompare(b));
  • Object sorting
onst users = [
{ name: 'Alice', age: 30 },
{ name: 'Bob', age: 22 },
{ name: 'Charlie', age: 27 }
];

const sortedUsersByAge = users.toSorted((a, b) => a.age - b.age);
const sortedUsersByName = users.toSorted((a, b) =>
a.name.localeCompare(b.name)
);

array.toReversed()

  • Reverse without mutating the original array.
const items = [1, 2, 3];
const reversedItems = items.toReversed();
console.log(reversedItems); // [3, 2, 1]
console.log(items); // [1, 2, 3]

Slice Vs Splice

Slice

Syntax => slice(start, end), end is not included

  • Return portion of an array
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];

console.log(animals.slice(0, 2));

Splice

Syntax => splice(start_index, number_of_elts_to_remove, …list_of_elts_to_add)

  • Remove elements with Splice
let array = [1,2,3,4,5];

array.splice(3, 1); //removes number 4
console.log(array)
  • Add elements with slice
let array = [1,2,3,4,5];

array.splice(3, 0, 'A', 'B', 'C'); //Add A,B,C
console.log(array)

Sorting

Sorting is in-place in JavaScript

  • Sort linear array
const array = [5,4,3,2,1];
array.sort()
console.log(array)
  • You can use array.sort() in similar fashion as array.toSorted() to sort strings and objects.

JS Map and Set

Map

  • Map is a collection of keyed data items, just like an Object. But the main difference is that Map allows keys of any type.
  • Avoid using map[key]=value or map[key] to set and get value from a map, instead use set and get methods
new Map()
– creates the map.
map.set(key, value)
– stores the value by the key.
map.get(key)
– returns the value by the key, undefined if key doesn’t exist in map.
map.has(key)
– returns true if the key exists, false otherwise.
map.delete(key)
– removes the element (the key/value pair) by the key.
map.clear()
– removes everything from the map.
map.size
– returns the current element count.
let map = new Map();

map.set('1', 'str1'); // a string key
map.set(1, 'num1'); // a numeric key
map.set(true, 'bool1'); // a boolean key

// remember the regular Object? it would convert keys to string
// Map keeps the type, so these two are different:
console.log(map.get(1)); // 'num1'
console.log(map.get('1') ); // 'str1'

console.log(map.size); // 3

Map Vs Object

  • For js object key must be string, otherwise it will be converted to string, however in map key can be anything(object, primitives)
const obj = {};

obj[12] = 'number of columns';
obj[{name: 'John'}] = 450;

console.log(obj); //{ '12': 'number of columns', '[object Object]': 450 }
const m = new Map();

m.set(12, 'number of columns');
m.set({name: 'John'}, 450);

console.log(m); //Map(2) { 12 => 'number of columns', { name: 'John' } => 450 }

Iteration

const priceMap = new Map([
['mac', 2400],
['iphone', 1200],
['samsung', 900]
]); //map can be created with array

for (let brand of priceMap.keys()) {
console.log(brand, priceMap.get(brand));
}


//or
priceMap.forEach((value,key, map) => {
console.log(key, value);
})

Set

  • A Set is a special type collection – “set of values” (without keys), where each value may occur only once.
  • Like map key can be any js type(number, boolean, array, object…)
new Set([iterable])
– creates the set, and if an iterable object is provided (usually an array), copies values from it into the set.

set.add(value)
– adds a value, returns the set itself.

set.delete(value)
– removes the value, returns true if value existed at the moment of the call, otherwise false.

set.has(value)
– returns true if the value exists in the set, otherwise false.

set.clear()
– removes everything from the set.

set.size
– is the elements count.
let set = new Set();

let john = { name: "John" };
let pete = { name: "Pete" };
let mary = { name: "Mary" };

// visits, some users come multiple times
set.add(john);
set.add(pete);
//set.add([1,2,34]);
set.add(john);
set.add(mary);

// set keeps only unique values
console.log( set.size ); // 3

for (let user of set) {
console.log(user); // John (then Pete and Mary)
}

Iteration

let set = new Set(["oranges", "apples", "bananas"]);

for (let value of set) console.log(value);

// the same with forEach:
set.forEach((value, valueAgain, set) => {
console.log(value);
});