# Bits of code

## Reduce array to objects in that array

```javascript
  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:**

```javascript
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?
```

```javascript
typeof  +"5" //returns number 
typeof `${5}` // returns string
```

## Dynamic Object

```javascript
let dynamicProperty ="Dynamic"
const user ={
  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

![](broken-reference)

```javascript
let intersection = arrA.filter(x => arrB.includes(x));
```

## Array Difference

![](broken-reference)

```javascript
let difference = arrA.filter(x => !arrB.includes(x));
```

## Symmetrical Difference

![](broken-reference)

```javascript
let difference = arrA
                 .filter(x => !arrB.includes(x))
                 .concat(arrB.filter(x => !arrA.includes(x)));
```

## Union

![](broken-reference)

```javascript
let union = [...new Set([...arrA, ...arrB)];
```

## find duplicates&#x20;

```javascript
  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.

Given a changed object and an array:

```javascript
const item = {...}
let items = [{id:2}, {id:3}, {id:4}];
```

Update the array with the new object by iterating over the array:

```javascript
items = items.map(x => (x.id === item.id) ? item : x)
```

## Check if Object has a property

Check if an object have a specific property&#x20;

```typescript
const hasOwnProperty = ( x: {}, k: K ): x is O &
                       { [key in K]: 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            
const isCurrentWorkspace = (v: unknown): v is PersonalOrOrg<string> 
                            => typeof v === 'object' && !!v 
                            && hasOwnProperty(v, 'type') 
                            && (v.type === 'personal' 
                            || (hasOwnProperty(v, 'organization') 
                            && typeof v.organization === 'string'))
```

## ParseJwt without lib&#x20;

```tsx
const parseJwt = (bearer: string) => {
  const [, token] = bearer.trim().split(' ');

  const base64Url = token.split('.')[1]; // token you get
  const base64 = base64Url.replace('-', '+').replace('_', '/');
  const decodedData = JSON.parse(Buffer.from(base64, 'base64').toString('binary'));

  return decodedData;
};

export { parseJwt };

```
