Thursday, 6 January 2022

Javascript data structure, map, array reduce, array some()

 Javascript data structure :

https://adrianmejia.com/data-structures-time-complexity-for-beginners-arrays-hashmaps-linked-lists-stacks-queues-tutorial/



Javascript maps :

https://www.geeksforgeeks.org/map-in-javascript/

https://www.w3schools.com/js/js_object_maps.asp


A Map holds key-value pairs where the keys can be any datatype.


A Map remembers the original insertion order of the keys.


A Map has a property that represents the size of the map.


// Create a Map
const fruits = new Map();

// Set Map Values
fruits.set("apples"500);
fruits.set("bananas"300);
fruits.set("oranges"200);

Or 

const fruits = new Map([

  ["apples", 500],

  ["bananas", 300],

  ["oranges", 200]

]);


fruits.get("apples");    // Returns 500


Javascript array Reduce :

https://www.w3schools.com/jsref/jsref_reduce.asp


Subtract all numbers in an array:

const numbers = [1755025];

document.getElementById("demo").innerHTML = numbers.reduce(myFunc);

function myFunc(total, num) {
  return total - num;
}

// result 100

Round all the numbers and display the sum:

const numbers = [15.52.31.14.7];
document.getElementById("demo").innerHTML = numbers.reduce(getSum, 0);

function getSum(total, num) {
  return total + Math.round(num);
}
// 24
ParameterDescription
function()Required.
A function to be run for each element in the array.
Reducer function parameters:
totalRequired.
The initialValue, or the previously returned value of the function.
currentValueRequired.
The value of the current element.
currentIndexOptional.
The index of the current element.
arrOptional.
The array the current element belongs to.
Javascript : some can be used together with filter
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some
The some() method tests whether at least one element in the array passes the test implemented by the provided function. It returns true if, in the array, it finds an element for which the provided function returns true; otherwise it returns false. It doesn't modify the array.
const array = [1, 2, 3, 4, 5];

// checks whether an element is even
const even = (element) => element % 2 === 0;

console.log(array.some(even));
// expected output: true



No comments:

Post a Comment