> For the complete documentation index, see [llms.txt](https://maissen.gitbook.io/maissen-grimoire/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://maissen.gitbook.io/maissen-grimoire/javascript-grimoire/bits-of-code.md).

# 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

![](/files/-M8PRTRvMnxa8sC0nizy)

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

## Array Difference

![](/files/-M8PRTRyvzVoDxljATzJ)

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

## Symmetrical Difference

![](/files/-M8PRTRzgvwfL7HGaYY_)

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

## Union

![](/files/-M8PRTS-sJqOkxTzcfoF)

```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 };

```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://maissen.gitbook.io/maissen-grimoire/javascript-grimoire/bits-of-code.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
