let array = [ { v1:"v1", v2:"v2" }, { v1:"v1", v2:"v2" }, { v1:"v1", v2:"v2" },];let result =array.reduce((currentArry, elementOfTheArry, Index) => {currentArry.push(elementOfTheArry.v1);return currentArry; // ********* Important ******}, []);console.log(result) // result = [ 'v1', 'v1', 'v1' ]
Coerce string into a number
Backticks reference
Backticks (`) are used to define template literals. Template literals are a new feature in ECMAScript 6 to make working with strings easier.
Features:
we can interpolate any kind of expression in the template literals.
They can be multi-line.
Note: we can easily use single quotes (') and double quotes (") inside the backticks (`).
Example:
var nameStr =`I'm "Rohit" Jindal`;
To interpolate the variables or expression we can use the ${expression} notation for that.
var name = 'Rohit Jindal';
var text = `My name is ${name}`;
console.log(text); // My name is Rohit Jindal
Multi-line strings means that you no longer have to use \n for new lines anymore.
Example:
const name = 'Rohit';
console.log(`Hello ${name}!
How are you?`);
Output:
Hello Rohit!
How are you?
typeof+"5"//returns number typeof`${5}`// returns string
Dynamic Object
let dynamicProperty ="Dynamic"constuser={ name :"maissen", email:"ayed.maissen@gmail.com", [dynamicProperty]:"this is dynamic"}console.log(user);/* Result :{ name: 'maissen', email: 'ayed.maissen@gmail.com', Dynamic: 'this is dynamic'}*/
Array intersection
let intersection =arrA.filter(x =>arrB.includes(x));
Array Difference
let difference =arrA.filter(x =>!arrB.includes(x));
Symmetrical Difference
let difference = arrA.filter(x =>!arrB.includes(x)).concat(arrB.filter(x =>!arrA.includes(x)));
Union
let union = [...newSet([...arrA,...arrB)];
find duplicates
let counts = {};array.forEach((x)=> { counts[x] = (counts[x] ||0)+1;})return counts
Javascript ES6/ES5 find in array and change
the map loops over each item in the items array and checks if that item has id the same as the id of the item in the const variable. If it finds one, it maps that item which is x to item which is the one in the const variable, otherwise it keeps the same element x in the items array.
consthasOwnProperty= ( x: {}, k:K ): x isO& { [key inK]: unknown } =>x.hasOwnProperty(k)// example to check if object v is an Object // supposedly with the type PersonalOrOrg // has a property type and type equal 'personal' or// has a property type and type equal 'organization' // with a property of organization of type sting constisCurrentWorkspace= (v:unknown): v isPersonalOrOrg<string> =>typeof v ==='object'&&!!v &&hasOwnProperty(v,'type') && (v.type ==='personal'|| (hasOwnProperty(v,'organization') &&typeofv.organization ==='string'))