Chrome Extension

javascript code snippets

How to Remove duplicate elements from array in JavaScript ?
//Method 1
// Defining a set of the cities
  let city = [
    "surat",
    "ahmedabad",
    "rajkot",
    "mumbai",
    "surat",
    "delhi",
    "ahmedabad",
    "anand",
  ];
  
  // For removing the duplicate values
  // we are using the Set() function
  let unique_city = [new Set(city)];
  
  // Printing the unique cities
  console.log(unique_city);

  //Output
  ["surat", "ahmedabad", "rajkot", "mumbai", "delhi"]

//Method 2

// Defining the unique cities from the above
  // array by using forEach loop
  let unique_city = [];
  city.forEach((c) => {
    if (!unique_city.includes(c)) {
      unique_city.push(c);
    }
  });
  console.log(unique_city);

  //Output
  ["surat", "ahmedabad", "rajkot", "mumbai", "delhi"]


//Method-3
var my_array = [5, 4, 7, 8, 9, 2, 7, 5, 4, 8, 7];
unique_array = my_array.filter((item, index, array) => array.indexOf(item) === index);
console.log("Unique Array is : " + unique_array);

//Method - 4
const arr = [
  { id: 1, name: "test1" },
  { id: 2, name: "test2" },
  { id: 2, name: "test3" },
  { id: 3, name: "test4" },
  { id: 4, name: "test5" },
  { id: 5, name: "test6" },
  { id: 5, name: "test7" },
  { id: 6, name: "test8" }
];

const filteredArr = arr.reduce((acc, current) => {
  const x = acc.find(item => item.id === current.id);
  if (!x) {
    return acc.concat([current]);
  } else {
    return acc;
  }
}, []);


//Method - 5
//Here's another possibility using the Map class constructor and values method:
const arr = [
  { id: 1, name: "test1" },
  { id: 2, name: "test2" },
  { id: 2, name: "test3" },
  { id: 3, name: "test4" },
  { id: 4, name: "test5" },
  { id: 5, name: "test6" },
  { id: 5, name: "test7" },
  { id: 6, name: "test8" }
];

const uniqueObjects = [...new Map(arr.map(item => [item.id, item])).values()]


//Method-6

		function removeDuplicates() {
			// Create an array of objects
			books = [
				{ title: "C++", author: "Bjarne" },
				{ title: "Java", author: "James" },
				{ title: "Python", author: "Guido" },
				{ title: "Java", author: "James" },
			];
			// Display the list of array objects
			console.log(books);
			// Declare a new array
			let newArray = [];
			// Declare an empty object
			let uniqueObject = {};
			// Loop for the array elements
			for (let i in books) {
				// Extract the title
				objTitle = books[i]['title'];
				// Use the title as the index
				uniqueObject[objTitle] = books[i];
			}
			// Loop to push unique object into array
			for (i in uniqueObject) {
				newArray.push(uniqueObject[i]);
			}
			// Display the unique objects
			console.log(newArray);
		}


  //Method-7
  function removeDuplicates() {
          // Create an array of objects
          books = [
              { title: "C++", author: "Bjarne" },
              { title: "Java", author: "James" },
              { title: "Python", author: "Guido" },
              { title: "Java", author: "James" },
          ];
          jsonObject = books.map(JSON.stringify);
          console.log(jsonObject);
          uniqueSet = new Set(jsonObject);
          uniqueArray = Array.from(uniqueSet).map(JSON.parse);
          console.log(uniqueArray);
}

//Method- 8
const arr = [
    {place: "here",  name: "x", other: "other stuff1" },
    {place: "there", name: "x", other: "other stuff2" },
    {place: "here",  name: "y", other: "other stuff4" },
    {place: "here",  name: "z", other: "other stuff5" }
]
function getUniqueListBy(arr, key) {
    return [...new Map(arr.map(item => [item[key], item])).values()]
}

//get unique by place
const arr1 = getUniqueListBy(arr, 'place');
//get unique by name
const arr2 = getUniqueListBy(arr, 'name')
Array reducce
//Reference ->  https://sebhastian.com/javascript-sum-array-objects/
//Sometimes, you need to count the sum of property in an array of objects. 
//For example, you may find an array of items, and you want to sum the total quantity a person must pay for the items
let cart = [
  {
    name: "JavaScript book",
    price: 4,
  },
  {
    name: "UGG Women's Hazel Ankle Boot",
    price: 79,
  },
  {
    name: "OXO Good Grips 11-Inch Balloon Whisk",
    price: 9,
  },
];
// totalPrice is 92
let totalPrice = cart.reduce(function (accumulator, item) {
  return accumulator + item.price;
}, 0);


//Perform multiple operations before returning the data
let cart = [
  {
    name: "JavaScript book",
    quantity: 3,
    price: 4,
  },
  {
    name: "UGG Women's Hazel Ankle Boot",
    quantity: 2,
    price: 79,
  },
  {
    name: "OXO Good Grips 11-Inch Balloon Whisk",
    quantity: 5,
    price: 9,
  },
];

// totalPrice is 215

let totalPrice = cart.reduce(function (accumulator, item) {
  return accumulator + item.quantity * item.price;
}, 0);



//Filter the array before reduce
let cart = [
  {
    name: "JavaScript book",
    quantity: 3,
    price: 4,
  },
  {
    name: "UGG Women's Hazel Ankle Boot",
    quantity: 2,
    price: 79,
  },
  {
    name: "OXO Good Grips 11-Inch Balloon Whisk",
    quantity: 5,
    price: 9,
  },
];

// totalPrice is 170

let totalPrice = cart
  .filter(
    (item) =>
      item.name === "JavaScript book" ||
      item.name === "UGG Women's Hazel Ankle Boot"
  )
  .reduce((accumulator, item) => {
    return accumulator + item.quantity * item.price;
  }, 0);
Regex for email validation in Javascript
function email_validator(my_email) {
    var email_pattern = /^(([^<>()[]\.,;:s@"]+(.[^<>()[]\.,;:s@"]+)*)|(".+"))@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}])|(([a-zA-Z-0-9]+.)+[a-zA-Z]{2,}))$/;
    if (email_pattern.test(my_email)) {
        console.log("Email is Valid");
    } else {
        console.log("Email is Invalid");
    }
}

email_validator("test@gmail.com"); // -> logs - Email is Valid
email_validator("test.com"); // -> logs - Email is Invalid
Compress or minify JSON using Javascript
var json_str = `[
    {
      "type": "people",
      "id": "30",
      "attributes": {
        "name": "John Deo",
        "age": 40,
        "gender": "male"
      }
    }
]`;

var minified_json = JSON.stringify(JSON.parse(json_str));
console.log(minified_json);
Javascript Sort() By Multiple Criteria
const teams = [
    {name: "Aviso1", state: true, priority: 1},
    {name: "aviso3", state: true, priority: 3},
    {name: "Aviso2", state: false, priority: 2},
    {name: "aviso4", state: true, priority: 4},
    {name: "aviso5", state: false, priority: 5},
    {name: "aviso6", state: true, priority: 6}
]
let formated = teams.sort((a, b) => a.state === b.state ?  a.priority - b.priority : b.state - a.state);

console.log(formated)


/*
[
  { name: 'Aviso1', state: true, priority: 1 },
  { name: 'aviso3', state: true, priority: 3 },
  { name: 'aviso4', state: true, priority: 4 },
  { name: 'aviso6', state: true, priority: 6 },
  { name: 'Aviso2', state: false, priority: 2 },
  { name: 'aviso5', state: false, priority: 5 }
]*/
How to use loop in React JSX
//USING FOR LOOP
<tbody>
    for (var i=0; i < items.length; i++) {
        <TableRow obj={items[i]} key={i}>
    }
</tbody>

//USING map function
<tbody>
    {items.map(function(item, index) {
        return <TableRow obj={item} key={index} />;
    })}
</tbody>

//ES6 SYNTAX
<tbody>
    {items.map((item, index) => <TableRow obj={item} key={index} />)}
</tbody>
allows keeping the URL while rendering a different page
beforeEnter(to, from){
//super code goes here
return {
        name: 'NotFound',
        // allows keeping the URL while rendering a different page
        params: { pathMatch: to.path.split('/').slice(1) },
        query: to.query,
        hash: to.hash,
      }
}
test113142
function hello() {
    return <h1>Hello world</h1>
}
Prettify JSON object or array using JSON.stringify
const json_data = {id: 10001, name: "Tokyo", show: "La Casa De papel"};
const pretty_json_str = JSON.stringify(json_data, undefined, 4);
Convert JSON data to String
const json_obj = { id: 1, name: "John Rick", pin: "000000" };
const json_str = JSON.stringify(json_obj);
Convert String to JSON Data
const str_data = '{"name": "Rick Grimes", "city": "New York","pincode": "000-000"}';

//Parse to json data
const json_data = JSON.parse(str_data);

//Using callback function in JSON.parse
const json_data2 = JSON.parse(str_data, function(key, value) {
    //DO something here
})
wait/delay function
method: {
    async function() {
        //first action
        await this.timeout(3000);//delay
        //second action
    },
    timeout(ms) {
        return new Promise(resolve => {
            window.setTimeout(resolve, ms)
        })
    }
}
Calculate square root of a number using javascript
const num = 100;
const sqrt = Math.sqrt(num);
Check if all array items are equal javascript
const allEqual = arr => arr.every(v => v === arr[0]);
allEqual([1,1,1,1]);  // true
Remove decimal points in numbers
Math.trunc(inputnumber) //truncate fractional part, also see below
Math.floor(inputnumber) //round down
Math.ceil(inputnumber) //round up
Math.round(inputnumber) //round to nearest integer
Load or preview html to Iframe using Javascript only
var html = '';
html += '<!DOCTYPE html>\n';
html += '<html lang="en">\n';
html += '<head>\n';
html += '</head>\n';
html += '<body>\n';
html += '<div>Hello World we are here...</div>';
html += '</body>\n';
html += '</html>';

(document.getElementById("iframe_id").contentWindow.document).write(html);
(document.getElementById("iframe_id").contentWindow.document).close();
Lodash - Get the last element of an array
const items = [10, 20, 30, 40, 50];
const last_item = _.last(items);
// => 50
Lodash - Create a string from array elements join with some separator
const arr = ["This", "is", "Programming", "world"];

// Join using -
const str = _.join(arr, '-');
// => This-is-Programming-world

// Join using space
const str_2 = _.join(arr, ' ');
// => This is Programming world
_.intersectionBy method in Lodash
const result1 = _.intersectionBy([2.8, 1.2], [2.3, 3.4], Math.floor);
console.log(result1);
Lodash - Get common values from multiple arrays
const arr1 = [10, 20, 30];
const arr2 = [5, 20, 40, 30];

const result1 = _.intersection(arr1, arr2);
// => [20,30]

const arr3 = [20];
const result2 = _.intersection(arr1, arr2, arr3);
// => [20]
Lodash - Get all elements of array except the last one
const arr = [10, 20, 30, 40, 50];

const result = _.initial(arr);
// => [10,20,30,40]
Lodash - Get index of first occurence of an array value
const names = ["Ankit", "Rick", "Maggie", "John", "Wick", "Rick", "Carol", "Maggie"];

//Get index of Rick
const rick_index = _.indexOf(names, 'Rick');
// => 1

//Get Index of Maggie start from - 3
const maggie_index = _.indexOf(names, 'Maggie', 3);
// => 7

//Get Index of Maggie start from - 1
const maggie_index_1 = _.indexOf(names, 'Maggie', 1);
// => 2
Lodash - get the first element from an array
const arr = [10, 20, 30, 40, 50];
const first_item = _.head(arr);
// => 10
Lodash - Convert paired Array to key value paired object
const subject = [
    ['name', 'Math'], 
    ['score', 90],
    ['dept', 'Mathematics']
];
const subject_obj = _.fromPairs(subject);
// => { "name": "Math", "score": 90, "dept": "Mathematics"}
Lodash - Flatten an array to a fixed depth
const arr = [
    [10], [20, 30, [40, [50]]], 60, [70, [80]]
];

//Flatten to 1 level
const result_1 = _.flattenDepth(arr, 1);
// => [10,20,30,[40,[50]],60,70,[80]]

//Flatten to 2 level
const result_2 = _.flattenDepth(arr, 2);
// => [10,20,30,40,[50],60,70,80]
Lodash - Flatten an array to multi levels deep
const arr = [10, [12, [15, 16]], [12, [30, [40]], 50]];
const result = _.flattenDeep(arr);

console.log(result);
// => [10,12,15,16,12,30,40,50]
Lodash - Flatten an array to single level deep
const arr = _.flatten([[10], [20, [33, [40]], 50]]);
console.log(arr);
// => [10,20,[33,[40]],50]
Lodash - Find item index from array by searching from the end
var subjects = [
    { 'name': 'Math', 'score': 70 },
    { 'name': 'Physics', 'score': 80 },
    { 'name': 'Chemistry', 'score': 80 },
    { 'name': 'English', 'score': 90 }
];

//It starts searching items from end
// Find index where subject name is Chemistry
const physics_index = _.findLastIndex(subjects, function (item) {
    return item.name == 'Physics'; 
});
console.log("Physics index is : " + physics_index);
// => 1

//Find Index where score is 80
const score_index = _.findLastIndex(subjects, ['score', 80]);
console.log(score_index);
//=> 2
Lodash - Get index of array item based on some condition
const users = [
    { 'user': 'John Deo', 'active': false },
    { 'user': 'Rick Grimes', 'active': false },
    { 'user': 'Negan', 'active': true }
];

//Find Index where user is - Rick Grimes
const index = _.findIndex(users, function (item) {
    return item.user == 'Rick Grimes';
});
console.log("User index is : " + index)
// => 1

// Find item index using full object match
const index_2 = _.findIndex(users, { 'user': 'Negan', 'active': true });
console.log("Object index is : " + index_2);
// => 2
Replace array values with another value Lodash
//REPLACE BY PASSING NEW VALUE ONLY
var arr = [1, 2, 3, 4, 5, 6];

_.fill(arr, '*');
console.log(arr);
// => ["*","*","*","*","*","*"]

_.fill(arr, 2);
console.log(arr);
// => [20,"#","#",70,80,90]

//REPLACE BY PASING - Value, start, end
const arr2 = [20, 50, 60, 70, 80, 90];
const start = 1;
const end = 3;
_.fill(arr2, '#', 1, 3);
console.log(arr2);
// => [20,"#","#",70,80,90]
Remove items begin from start until given condition is false Lodash
var users = [
    { 'user': 'Ankit', 'active': false },
    { 'user': 'John', 'active': true },
    { 'user': 'Deo', 'active': false }
];

const result = _.dropWhile(users, function (o) {
    return !o.active;
});
Remove items starting from last untill given condition is false Lodash
var users = [
    { 'user': 'Ankit', 'active': true },
    { 'user': 'John', 'active': false },
    { 'user': 'Deo', 'active': false }
];

const result = _.dropRightWhile(users, function (o) { 
    return !o.active;
});

// { 'user': 'Ankit', 'active': true }
Remove last n elements from an array using Lodash
const arr = [1, 2, 3, 4, 5, 6, 7];

//remove last element (n=1) by default
const arr1 = _.dropRight(arr);

//remove last 3 elements
const arr2 = _.dropRight(arr, 3);

//remove last 5 elements
const arr3 = _.dropRight(arr, 5);
Remove first n elements from an array using Lodash
const arr = [1, 2, 3, 4, 5, 6, 7];

//remove first element (n=1) by default
const arr1 = _.drop(arr);

//remove first 3 elements
const arr2 = _.drop(arr, 3);

//remove first 5 elements
const arr3 = _.drop(arr, 5);
Get all values from an array which does not exist in other array Lodash
const arr1 = [2, 1, 5, 6];
const arr2 = [2, 3, 10, 1];

//GET VALUES FROM arr1 that does not exist in arr2
const diff_arr = _.difference(arr1, arr2);
Merge multiple arrays and strings into single array using Lodash
const str = 50;
const arr1 = [20];
const arr2 = [30, 35];
const arr3 = [[10]]

const final_arr = _.concat(str, arr1, arr2, arr3);
Remove all false, null, undefined and empty values from array using Lodash
const arr = [5, 'one', 0, 1, false, 2, NaN, '', 3, undefined];
const new_arr = _.compact(arr)
Break an array into fixed length array groups using lodash in Javascript
const arr = ['one', 'two', 'three', 'four', 'five'];
const arr_chunks = _.chunk(arr, 2);
Get all values as array items from an Object in Javascript
const obj = {
    "id": 20,
    "name": "John Deo",
    "dept": "Computer",
    "pincode": "11111"
};

var obj_values = Object.values(obj);
Get all keys from an object using Javascript
var obj = {
    "name": "Ankit",
    "username": "ankit01",
    "status": "active",
    "contact": "mail"
};

var all_keys = Object.keys(obj);
Convert object {key: value} to Array [[key, value]] Javascript
const obj = { a: 1, b: 2, c: 3 };

const entries = Object.entries(obj);
Check if a string is Palindrome or not using Javascript
function palindrome_checker(str) {
    const converted_str = str.split('').reverse().join('');
    if (str === converted_str) {
        console.log(str + " : String is Palindrome");
    } else {
        console.log(str + " : String is not Palindrome");
    }
}

palindrome_checker('deified');
palindrome_checker('Ankit');
Convert a String to Number or Integer in Javascript
const str = "200";
var num = parseInt(str);
Swapping two values using Destructuring in Javascript
let a = 5;
let b = 8;
[a, b] = [b, a]

console.log([a, b])
Convert a Number or Integer to String in Javascript
const num = 10;
const str = num.toString();
Assign default values to function parameters in Javascript
const func = (arr, arg2 = 0, len = arr.length) => { // Here arg2 and len are parametes with default values.
    return len;
}
const result = func([10, 30, 40, 50, 60]);
console.log(result);
Combine or merge two or multiple arrays into single array in Javascript
const users1 = ['Ankit', 'Gaurav'];
const users2 = ['Abadhesh', 'Sourabh'];
const users3 = ['Arun', 'Avinash'];

//FIRST METHOD - using ...
const all_users1 = [...users1, ...users2, ...users3];

//SECOND METHOD - using .concat()
const all_users2 = users1.concat(users2).concat(users3)
Pass multiple arguments when calling a function which takes single argument Javascript
function func_name(...allArgs) {
    console.log("Paraameter at 3th position : " + arguments[2]);
    console.log("Paraameter at 6th position : " + arguments[5]);
}

func_name("value1", "value2", "value3", "value4", "value5", "value6");
Use of ?? (Nullish Coalescing Operator) in Javascript
const user_name = null ?? 'Ankit';
// Output: "Ankit"

const number = 0 ?? 40;
// Output: 0
Optional Chaining on Javascript Object
const user = {
  admin: {
    name: "John Deo"
  }
};
user.admin?.name;
// "John Deo"
user.admi?.name;
// undefined
user.admi.name
// TypeError: Cannot read property 'name' of undefined
Concatenate multiple objects into one using Javascript
const user = {
    name: 'John Deo',
    gender: 'Male'
};
const role = {
    admin: '1'
};
const details = {
    email: 'email@domain.com',
    city: 'New York',
};

const final_object = { ...user, ...role, ...details };

console.log(final_object);
How to use Ternary Operator in place of if else statements Javascript
//Simple If else condition using Ternary Operator
const score = 15;
const score_checker = score > 20 ? 'Score is grater than 20' : 'Score is less than 20';
console.log(score_checker);

//Nested If else conditions can be written using Ternary Operator
function check_number(num) {
    return num > 7 ? 'Number is greater than 7'
        : num < 7 ? 'Number is less than 7'
            : num === 7 ? 'Number is equals to 7' : "";
}

console.log(check_number(7));
console.log(check_number(6));
console.log(check_number(10));
Calculate the frequency of characters in a string using Javascript
const str = 'CoNgratulations';

const letters = {};
for (let char of str.toLowerCase()) {
    letters[char] = letters[char] + 1 || 1;
}

console.log(letters);
Remove duplicate values from an array in Javascript
var my_array = [5, 4, 7, 8, 9, 2, 7, 5, 4, 8, 7];

// First Method
unique_array = my_array.filter((item, index, array) => array.indexOf(item) === index);
console.log("Unique Array is : " + unique_array);

// Second Method
var another_uni_arr = [...new Set(my_array)];
console.log("Another Unique Array is : " + another_uni_arr);
Use of logical operators to reduce if else statements Javascript
function run_func(number) {
    // set number to 35 if it is not already set
    number = number || 35;
    console.log("Number is : " + number);
}

const check_this_var = 20;
check_this_var === 20 && run_func();
// SAME AS - if (check_this_var === 20) { run_func(); }
// Output: 10

check_this_var === 5 || run_func();
// SAME AS if (check_this_var != 5) { run_func(); }
// Output: 10
Remove empty, false, undefined values from array Javscript
var my_arr = [4, '', 0, 10, 7, '', false, 10];
my_arr = my_arr.filter(Boolean);
console.log(my_arr);
Get the sum of array values using Javascript - Solved
const myarr = [10, 23, 32, 65, 7, 24];
const sum_of_array = myarr.reduce((a, b) => a + b);
console.log(sum_of_array);
Find the maximum value from an array using Javascript
const myarr = [10, 23, 32, 65, 7, 24];
const max_value = myarr.reduce((a, b) => a > b ? a : b);
console.log(max_value);
Find the minimum value from an array javascript
const myarr = [10, 23, 65, 7, 24];
const min_val = myarr.reduce((a, b) => a < b ? a : b);
console.log(min_val);
Create fixed length array with blank values in it Javascript
var my_arr = Array(7).fill('');

console.log(my_arr);
rascunho
https://dev.to/techygeeky/top-20-javascript-tips-and-tricks-to-increase-your-speed-and-efficiency-283g
Run a Javascript function after user finished writing in the input field
var type_timer;
var finished_writing_interval = 3000;
var my_input = document.getElementById("my_input");

//Start timeout when user start typing
my_input.addEventListener('keyup', function () {
  clearTimeout(type_timer);
  type_timer = setTimeout(finished_typing, finished_writing_interval);
});

//Clear timeout on key down event
my_input.addEventListener('keydown', function () {
  clearTimeout(type_timer);
});

//This function runs when user has finished writing in input
function finished_typing () {
    console.log("User finished typing");
    //Do something here ...
}
Scroll to the bottom of a div using Javascript
var my_div = document.getElementById("my_div");
my_div.scrollTop = my_div.scrollHeight;
Run a function every 5 seconds interval using Javascript
var inverval_timer;

//Time in milliseconds [1 second = 1000 milliseconds ]    
inverval_timer = setInterval(function() { 
    console.log("5 seconds completed");
}, 5000);
    
//IF you want to stop above timer
function stop_timer() {
    clearInterval(inverval_timer); 
}
Remove new line separator from start and end positions of string in Javascript
my_str = "\n\n Hello World \n\n\n";
my_str = my_str.replace(/^\s+|\s+$/g, '');
console.log(my_str);
Call custom method on form submit redux form
//create a file submit.js and write method to call on form submit
import { SubmissionError } from 'redux-form';

const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));

function submitMethod(values) {
    return sleep(1200).then(() => { // simulate server latency
        if (!['alex', 'july'].includes(values.firstname)) {
            throw new SubmissionError({
                firstname: 'First name you entered is incorrect',
                _error: 'Not able to find First Name!',
            });
        } else {
            window.alert(`Submitted Object is :\n ${JSON.stringify(values, null, 2)}`);
        }
    });
}

export default submitMethod;

//create a file - MyValidationForm.js and design your form there to call above submitMethod in the form 
import React from 'react'
import { Field, reduxForm } from 'redux-form'
import submitMethod from './submit'

const renderThisInput = ({ input, label, type, meta: { touched, error } }) => (
  <div>
    <label>{label}</label>
    <div>
      <input {...input} placeholder={label} type={type} />
      {touched && error && <span>{error}</span>}
    </div>
  </div>
)

const MyValidationForm = props => {
  const { error, handleSubmit, pristine, reset, submitting } = props
  return (
    <form onSubmit={handleSubmit(submit)}> //Calling - submitMethod here from submit.js
      <Field
        name="firstname"
        type="text"
        component={renderThisInput}
        label="First Name"
      />
      <Field
        name="lastname"
        type="text"
        component={renderThisInput}
        label="Last Name"
      />
      {error && <strong>{error}</strong>}
      <div>
        <button type="submit" disabled={submitting}>
          Check Values
        </button>
        <button type="button" disabled={pristine || submitting} onClick={reset}>
          Rest Form
        </button>
      </div>
    </form>
  )
}

export default reduxForm({
  form: 'myValidationForm'
})(MyValidationForm)
Enter only number field validation redux form
const numberValidator = value => value && isNaN(Number(value)) ? 'Must be a number' : undefined

<Field 
    name="totalScore" 
    type="number"
    component={renderField}
    label="Total Score"
    validate={[ numberValidator ]}
/>
Apply multiple validation on same field redux form
const requiredValidator = (value) => (value ? undefined : "This field is required");
const maxLengthValidator = (max) => (value) =>
  value && value.length > max ? `Field sust be ${max} characters or less` : undefined;
const inputMaxLength = maxLengthValidator(10);

<Field
    name="firstName"
    type="text"
    component={renderField}
    label="Fiest Name"
    validate={[requiredValidator, inputMaxLength]}
/>
Order and find elements
carlist.map(element => 
console.log(element.brand +" = "+ element['models'].length )); 

console.log("result ==" + JSON.stringify(carlist.filter(element => element['brand'] ==  'Renault'),null,4)); 



var formatedlsit = []; 
var asceding = []; 
var desceding = []; 


formatedlsit = carlist.map(item => ({
        brand: item.brand,
        totalOfmodels: item.models.length
}));


console.log('--------------------------------------------------')

//console.log('formatedlist');
//console.log(JSON.stringify(formatedlsit, null, 4 ));

/*  asceding = formatedlsit.sort(function(a, b){return a.totalOfmodels - b.totalOfmodels});
desceding =  formatedlsit.sort(function(a, b){return b.totalOfmodels - a.totalOfmodels}); 
console.log('------------------ crescente--------------------------------')
console.log(JSON.stringify(asceding, null, 4 ));
console.log('-------------------decrescente-------------------------------')
console.log(JSON.stringify(desceding, null, 4 ));
console.log("mais modelos " + asceding[0].brand);
console.log("menos modelos" + desceding[0].brand);  */ 

 console.log(formatedlsit.sort(function(a, b){return a.totalOfmodels - b.totalOfmodels}));
console.log(formatedlsit.sort(function(a, b){return b.totalOfmodels - a.totalOfmodels}));
Apply required field validation on redux form fields
import React from 'react'
import { Field, reduxForm } from 'redux-form'

const requiredValidator = value => value ? undefined : 'Required'

const renderField = ({ input, label, type, meta: { touched, error, warning } }) => (
  <div>
    <label>{label}</label>
    <div>
      <input {...input} placeholder={label} type={type}/>
      {touched && ((error && <span>{error}</span>) || (warning && <span>{warning}</span>))}
    </div>
  </div>
)

const FieldLevelValidationForm = (props) => {
  const { handleSubmit, pristine, reset, submitting } = props
  return (
    <form onSubmit={handleSubmit}>
      <Field name="firstname" type="text"
        component={renderField} label="First Name"
        validate={[ requiredValidator ]}
      />
      <div>
        <button type="submit" disabled={submitting}>Submit</button>
        <button type="button" disabled={pristine || submitting} onClick={reset}>Reset</button>
      </div>
    </form>
  )
}

export default reduxForm({
  form: 'fieldLevelValidation' // a unique identifier for this form
})(FieldLevelValidationForm)
Email Validation on Field Redux Form
import React from 'react'
import { Field, reduxForm } from 'redux-form'

const emailValidation = value =>
  value && !/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(value) ?
  'Invalid email address' : undefined

const renderField = ({ input, label, type, meta: { touched, error, warning } }) => (
  <div>
    <label>{label}</label>
    <div>
      <input {...input} placeholder={label} type={type}/>
      {touched && ((error && <span>{error}</span>) || (warning && <span>{warning}</span>))}
    </div>
  </div>
)

const EmailValidationForm = (props) => {
  const { handleSubmit, pristine, reset, submitting } = props
  return (
    <form onSubmit={handleSubmit}>
      <Field 
        name="email" 
        type="email"
        component={renderField}
        label="Email"
        validate={emailValidation}
      />
      <div>
        <button type="submit" disabled={submitting}>Submit</button>
        <button type="button" disabled={pristine || submitting} onClick={reset}>Reset</button>
      </div>
    </form>
  )
}

export default reduxForm({
  form: 'EmailValidationForm'
})(EmailValidationForm)
Radio Button Input field in Redux Form
<div>
    <label>Choose Color</label>
    <div>
        <label>
            <Field name="color_selection" component="input" type="radio" value="green" />
            <span>Green</span>
        </label>
        <label>
            <Field name="color_selection" component="input" type="radio" value="red" />
            <span>Red</span>
        </label>
        <label>
            <Field name="color_selection" component="input" type="radio" value="blue" />
            <span>blue</span>
        </label>
    </div>
</div>
Add Input fields in Redux Form
import { Field, reduxForm } from 'redux-form';

<Field
    name="textField"
    component="input"
    type="text" //This can be password, email, number, etc
    placeholder="Text type field"
/>
Create a simple Login Form using Redux Form
import React, { Component } from 'react'
import { reduxForm, Field } from 'redux-form'

const renderInput = field =>   // render input and errors
    <div>
        <input {...field.input} type={field.type}/>
        { field.meta.touched && field.meta.error &&
            <span className="error">{field.meta.error}</span>
        }
    </div>

class LoginForm extends React.Component {
    render() {
        const { handleSubmit } = this.props

        return (
            <form onSubmit={handleSubmit}>
                <div className="ctrl_group">
                    <label htmlFor="username">Username</label>
                    <Field
                        name="username"
                        component={renderInput}
                        type="text"/>
                </div>

                <div className="ctrl_group">
                    <label htmlFor="password">Password</label>
                    <Field
                        name="password"
                        component={renderInput}
                        type="password"/>
                </div>

                <button type="submit">Submit</button>
            </form>
        )
    }
}

export default reduxForm({
  form: 'LoginForm'
})(LoginForm)
Add redux form reducer to store
import { createStore, combineReducers } from 'redux'
import { reducer as rformReducer } from 'redux-form'

const rootReducer = combineReducers({
  form: rformReducer
})

const store = createStore(rootReducer)
Get selected option text using jQuery
var selected_text = $("select option:selected").text();
console.log(selected_text);

$(document).on("change", "select", function() {
    var option_text = $('option:selected', this).text();
    console.log(option_text);
});
Run VueJs Server/Project
npm run serve
jquery linq
https://www.buildinsider.net/web/jqueryref/059
https://qiita.com/nishiurahiroki/items/5fe52bbcbb91d3181bbd#%E5%80%A4%E3%81%AE%E3%82%BB%E3%83%83%E3%83%88value
https://www.it-swarm-ja.tech/ja/jquery/1%E7%A7%92%E3%81%94%E3%81%A8%E3%81%ABajax%E3%83%AA%E3%82%AF%E3%82%A8%E3%82%B9%E3%83%88%E3%82%92%E5%AE%9F%E8%A1%8C%E3%81%99%E3%82%8B/1042450943/
Set default date in Jquery UI datepicker
$("#dateId").datepicker({
    defaultDate: '03/28/2020'
});
Check if a variable is null, empty, undefined or false Javascript
if (variable_name) {
    //variable_name will not be null, empty, undefined or false
}
murata vue.js 公式ドキュメント
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    

    <div id="app">
        app1
        {{ message }}
      </div>


      <div id="app-2">
          app2
        <span v-bind:title="message">
          Hover your mouse over me for a few seconds
          to see my dynamically bound title!
        </span>
      </div>

      <div id="app-3">
          app3
        <span v-if="seen">Now you see me</span>
      </div>


      <div id="app-4">
          app4
        <ol>
          <li v-for="todo in todos">
            {{ todo.text }}
          </li>
        </ol>
      </div>
      
      <div id="app-5">
          app5
        <p>{{ message }}</p>
        <button v-on:click="reverseMessage">Reverse Message</button>
      </div>


      <div id="app-6">
          app6
        <p>{{ message }}</p>
        <input v-model="message">
      </div>



      <div id="app-7">
          app7
        <ol>
          <!--
            Now we provide each todo-item with the todo object
            it's representing, so that its content can be dynamic.
            We also need to provide each component with a "key",
            which will be explained later.
          -->
          <mitsu-item
            v-for="item in groceryList"
            v-bind:mitsutodo="item"
            v-bind:key="item.idmitsu"
          ></mitsu-item>
        </ol>
      </div>





    <script src="https://cdn.jsdelivr.net/npm/vue@2"></script>

<script>
    var app = new Vue({
  el: '#app',
  data: {
    message: 'Hello mitsu!'
  }
})



var app2 = new Vue({
  el: '#app-2',
  data: {
    message: 'You loaded this page on ' + new Date().toLocaleString()
  }
})

var app3 = new Vue({
  el: '#app-3',
  data: {
    seen: true
  }
})


var app4 = new Vue({
  el: '#app-4',
  data: {
    todos: [
      { text: 'Learn JavaScript' },
      { text: 'Learn Vue' },
      { text: 'Build something awesome' }
    ]
  }
})


var app5 = new Vue({
  el: '#app-5',
  data: {
    message: 'Hello Vue.js!'
  },
  methods: {
    reverseMessage: function () {
      this.message = this.message.split('').reverse().join('')
    }
  }
})


var app6 = new Vue({
  el: '#app-6',
  data: {
    message: 'Hello Vue!'
  }
})


Vue.component('mitsu-item', {
  props: ['mitsutodo'],
  template: '<li>{{ mitsutodo.nakami }}</li>'
})

var app7 = new Vue({
  el: '#app-7',
  data: {
    groceryList: [
      { idmitsu: 0, nakami: 'Vegetables' },
      { idmitsu: 1, nakami: 'Cheese' },
      { idmitsu: 2, nakami: 'Whatever else humans are supposed to eat' }
    ]
  }
})



</script>



</body>
</html>
Deploy React application from subdirectory
// OPEN  package.json FILE AND ADD "homepage": "/folder-name/"
{
    "name": "app name",
    "version": "0.1.0",
    ...
    "homepage": "/folder-name/" //ADD THIS AT THE BOTTOM
}

//OPEN ROUTING FILE AND ADD basename={'folder-name'}
<Router history={browserHistory} basename={'folder-name'}>
  <Route path="/" component={App} />
</Router>
Editorjs blocks - JSON to HTML javascript
function jsonToHtml(jsonStr) {
    obj = JSON.parse(jsonStr);

    html = '';
    obj["blocks"].forEach(function(block, index) {
        switch (block['type']) {
            case 'paragraph':
                html += '<p>'+ block['data']['text'] +'</p>';
                break;
            
            case 'header':
                html += '<h'+ block['data']['level'] +'>'+ block['data']['text'] +'</h'+ block['data']['level'] +'>';
                break;

            case 'raw':
                html += block['data']['html'];
                break;

            case 'list':
                lsType = (block['data']['style'] == 'ordered') ? 'ol' : 'ul';
                html += '<' + lsType + '>';
                block['data']['items'].forEach(function(item, index) {
                    html += '<li>' + item + '</li>';
                });
                html += '</' + lsType + '>';
                break;
            
            case 'code':
                html += '<pre><code class="language-'+ block['data']['lang'] +'">'+ block['data']['code'] +'</code></pre>';
                break;
            
            case 'image':
                html += '<div class="img_pnl"><img src="'+ block['data']['file']['url'] +'" /></div>';
                break;
            
            default:
                break;
        }
    });
    
    return html;
}
Util Array Examples
const allLanguages = [ 'ES', 'EN', 'DE' ]
const usedLanguages = [ { id: 1, lang: 'EN' } ].map(e => e.lang);

var result = allLanguages.filter(e => !usedLanguages.includes(e));
console.log(result)


=================



 const myArrayFiltered = this.AllGroupActive.filter(array => this.workFrontAnomalyType.developmentStageGroupId.some(filter => filter === array.id ));
 const checkAllActive = myArrayFiltered.every(item => item.active);



 ===========================================================
var arr1 = ['a', 'b'];
var arr2 = ['a', 'b', 'c', 'd'];

  let intersection = arr1.filter(x => arr2.includes(x));
  let difference = arr1.filter(x => !arr2.includes(x));

   symmetric difference,

   let difference = arr1
                 .filter(x => !arr2.includes(x))
                 .concat(arr2.filter(x => !arr1.includes(x))); 
=======================

someValues.forEach((element, index) => {
    console.log(`Current index: ${index}`);
    console.log(element);
});

============

 removeAnomaly(anomaly: WorkFrontAnomaly){
        var index = this.workFrontAnomalies.indexOf(anomaly);

        if(index != -1){
            this.workFrontAnomalies.splice(index, 1);
        }
    }
Navigate or link to another page React
//INSTALLATTION - npm install react-router-dom
import React from "react";
import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";

export default function App() {
    return (
        <div>
            <ul>
                <li><Link to="/">Home</Link></li>
                <li><Link to="/about">About</Link></li>
                <li><Link to="/contact">Contact</Link></li>
            </ul>

            <Router>
                <Route exact path="/" component={Home} />
                <Route exact path="/about" component={About} />
                <Route exact path="/contact" component={Contact} />
            </Router>
        </div>
    );
}
Javascript Map and Filter together
data
    .filter(item => item.workFrontAnomalyTypeId === this.WorkFrontAnomalyTypeId)
    .map(anomaly => ({
        name: anomaly.name,
        id: anomaly.id,
        active: anomaly.active,
        workFrontAnomalyTypeId: anomaly.workFrontAnomalyTypeId,
        impedative: anomaly.impedative
    }));
Copy multiple files Gulp
var gulp = require('gulp');

gulp.task('copy_files', function() {
    return gulp.src([
            'app/icon.png', 
            'app/manifest.json', 
            'app/index.html', 
            'app/filename.js'
            ]).pipe(gulp.dest('dist'))
});
Render item condition based React
function template() {
    const renderItem = true;

    return <div>
        {renderItem &&
            <div>This will render if renderItem is true</div>
        }
    </div>
}
Get index in map React
function items() {
    const nums = [1, 2, 3, 4];
    return <div>
        {nums.map( (num, index) => 
            <div key={index.toString()}>{num}</div>
        )}
    </div>;
}
List and map in React
function subjectList() {
    const subjects = [
        {"name": "Physics", "score": "9"},
        {"name": "Chemistry", "score": "7"},
        {"name": "Math", "score": "10"}
    ];
    const subjectItems = subjects.map( (subject, index) =>
        <div class="item" key={index.toString()}>
            Subject is {subject.name}
            Score is {subject.score}
        </div>
    );
    return <div class="items">{subjectItems}</div>
}
For loop in Javascript
for (var i = 0; i < 5; i++) {
    console.log(i);
}
Watch files in Gulp
var gulp = require('gulp');

gulp.task('watch', function() {
    gulp.watch('app/scss/*.scss', gulp.series('sass'));
    gulp.watch('app/js/*.js', gulp.series('minifyjs'));
});
Default task in Gulp
var gulp = require('gulp');

gulp.task('task1', function() { /** TASK 1 Process */ });

gulp.task('task2', function() { /** TASK 1 Process */ });

gulp.task('default', gulp.series(
    'task1',
    'task2'
));
Compress images using Gulp
//Installation - npm install --save-dev gulp-imagemin
const gulp = require('gulp');
const imagemin = require('gulp-imagemin');
 
gulp.task('compress_img', function() {
    return gulp.src('src/images/*')
            .pipe(imagemin())
            .pipe(gulp.dest('dist/images'))
})
SCSS to CSS Gulp
//Installation - npm install node-sass gulp-sass --save-dev

var gulp = require('gulp');
var sass = require('gulp-sass');

gulp.task('sass_', function() {
    return gulp.src('app/scss/*.scss')
        .pipe(sass({outputStyle: 'compressed'}))
        .pipe(gulp.dest('app/content/css'));
});
Minify js using Gulp
//Installation - npm install --save-dev gulp-uglify
var gulp = require('gulp');
var uglify = require('gulp-uglify');

gulp.task('minifyjs', function () {
  return gulp.src('lib/*.js')
            .pipe(uglify())
            .pipe(gulp.dest('dist'));
});
Minify CSS using Gulp
//INSTALLATION - npm install gulp-clean-css --save-dev
var gulp = require('gulp');
var cleanCSS = require('gulp-clean-css');

gulp.task('css_minify', function() {
    return gulp.src('app/css/*.css')
            .pipe(cleanCSS())
            .pipe(gulp.dest('dist/css'));
});
Delete files and folders Gulp
//USING PACKAGE - del 
//INSTALLATION - npm install del
var gulp = require("gulp");
var del = require("del");

gulp.task("delete_task", function() {
    return del(['app/build/**'], {force: true});
});
Get and set storage in chrome extension
chrome.storage.sync.set({name: value}, function() {
    console.log('value is : ' + value);
});

chrome.storage.sync.get(['name'], function(result) {
    console.log('name is : ' + result.name);
});
open link in new tab using javascript
window.open('https://devsheet.com', '_blank');
Loop through object on template Vuejs
//If OBJECT IS AS BELOW
const fruits = {
    "name": "Mango",
    "color": "Yellow",
    "taste": "sweet",
    "quantity": 10
};

<div v-for="(value, key) in fruits" :key="key">
    <div>{{ key }} - {{value}}</div>
</div>
Remove item from array in Javascript
const myArray = [2, 5, 9];

const removeIndex = 2;
myArray.splice(removeIndex, 1);

console.log(myArray);
How to Check if Arrays in a Object Are All Empty
var allEmpty = Object.keys(obj).every(function(key){
return obj[key].length === 0
})

//filter 
function isUnPopulatedObject(obj) { 
    return Object.keys( obj ).filter( function(key){
      return obj[ key ].length > 0;  //if any array has a property then filter will return this key.
    }).length == 0; //used == here since you want to check if all are empty
}

//every 
function isUnPopulatedObject(obj) { 
    return Object.keys( obj ).every( function(key){
      return obj[ key ].length == 0;  
    }); 
}

//some 
function isUnPopulatedObject(obj) { 
    return Object.keys( obj ).some( function(key){
      return obj[ key ].length > 0;  
    }) === false; 
}

//es8 
const objectIsEmpty = obj => Object.values(obj).every(
    val => Array.isArray(val) && val.length === 0
);

//every 2 sample 
function objectIsEmpty(obj) {
    return Object.keys(obj).every(key => 
      Array.isArray(obj[key]) && obj[key].length
    );
}
CODE GENERATOR
function makeid(length) {
   var result           = '';
   var characters       = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
   var charactersLength = characters.length;
   for ( var i = 0; i < length; i++ ) {
      result += characters.charAt(Math.floor(Math.random() * charactersLength));
   }
   return result;
}

console.log(makeid(5));
Truthy and Falsy in JavaScript
/*In JavaScript, truthy are expressions which evaluates to boolean true value and falsy evaluates to boolean false value. Unlike other languages, true and false values are not limited to boolean data types and comparisons. It can have many other forms. */


//Falsy Values
false
0 Both positive and negative
0n BigInt, when used as a boolean, follows the same rule as a Number
''
null
undefined
NaN
let a = false
    let b = 0
    let c = -0
    let d = 0n
    let e = ''
    let f = null
    let g = undefined
    let h = NaN
    console.log(Boolean (a))
    console.log(Boolean (b))
    console.log(Boolean (c))
    console.log(Boolean (d))
    console.log(Boolean (e))
    console.log(Boolean (f))
    console.log(Boolean (g))
    console.log(Boolean (h))

//Truthy Values
true
{} An object (whether empty or not)
[] An array (whether empty or not)
25 Numbers (whether positive or negative)
'true' Non empty strings
'false' Non empty strings
new Date() Date object
12n BigInt, when used as a boolean, follows the same rule as a Number
Infinity
JavaScript ES6 filtering object with multiple params
let equipmentsReturn = [
                { id: 23, typeId : 214 , groupId :10, tag:"CM0091"}, 
                { id: 11, typeId : 314 , groupId :10, tag:"CM009"}, 
                { id: 435, typeId : 412 , groupId :10, tag:"CM009"},
                { id: 23231, typeId : 2142312 , groupId :10, tag:"CM009"}, 
                { id: 1231231, typeId : 31444 , groupId :10, tag:"CM009"}, 
                { id: 48882, typeId : 412331 , groupId :10, tag:"CM009"},
                { id: 20, typeId : 12356734 , groupId :10, tag:"CM009"},
                { id: 31, typeId : 8888888 , groupId :10, tag:"CM009"},
                { id: 31236566, typeId : 100 , groupId :10, tag:"CM009"},
                { id: 31236566, typeId : 200 , groupId :10, tag:"CM009"}

            ];
            let arraytype = [214];
            let arraygroupId = [ 86, 77];
            let arraytag = ["CM119","CM977"];

            const filtered = equipmentsReturn.filter(({ typeId ,groupId , tag}) =>
            arraytype.includes(typeId) || arraygroupId.includes(groupId) || arraytag.includes(tag) );
            
           console.log(filtered);
Javascript Async/Await ES7
async function foo() {
    const myPromise = new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve("Parwinder"); // resolves with "Parwinder" after 2 seconds
        }, 2000);
    });

    // will not move to the next line until myPromise resolves/rejects
    const name = await myPromise;
    // the execution pauses (or awaits) for the promise

    console.log(name); // Parwinder
}

foo();
Get total sum of specif attribute inside of array of objects
let products = [{
  "id": 1,
  "product_name": "Forester",
  "price": 10
}, {
  "id": 2,
  "product_name": "Rainier",
  "price": 10
}, {
  "id": 3,
  "product_name": "Yukon Denali",
  "price": 10
}, {
  "id": 4,
  "product_name": "Regal",
  "price": 10
}, {
  "id": 5,
  "product_name": "Alcyone SVX",
  "price": 5
}];

let totalPrice = products.reduce((accumulator, current) => {
          return accumulator + current.price;
        }, 0);

//totalPrice 45
Find the shortest string in array
let arr = ["aaaa", "aa", "aa", "aaaaa", "a", "aaaaaaaa"];

console.log(
  arr.reduce(function(a, b) {
    return a.length <= b.length ? a : b;
  })
)
// result a
Finding the max/min value of an attribute in an array of objects
//Mapping formated counting 
var arr = ['one', 'two', 'three']
arr.map(element => ({ valor : element.length, descricao: element}) );

//result of the code above and look like this array...
let array =[
    {
        "valor": 3,
        "descricao": "one"
    },
    {
        "valor": 3,
        "descricao": "twsso"
    },
    {
        "valor": 5,
        "descricao": "threexx"
    }
];

let maxvalue = Math.max.apply(Math,array.map(function(o){return o.valor;}))
let minvalue = Math.min.apply(Math,array.map(function(o){return o.valor;}))

let objmax = array.find(function(o){ return o.valor == maxvalue; })
let objmin = array.find(function(o){ return o.valor == minvalue; })

console.log("max word value" + JSON.stringify(objmax)); 
console.log("min word value" + JSON.stringify(objmin));
Get a bigger word from a javascript array
console.log(longestStringReduce(['boop', 'bloomburg', 'hello']));

function longestStringReduce(arr) {
  return arr.reduce((a, b) => a.length < b.length ? b : a, "");
}

//bigger word
//bloomburg
Get Top MAX and MIN itens inside array Javascript
var maxPoints = [];
var scoreByPattern = [93,17,56,91,98,33,9,38,55,78,29,81,60];

function cloneArray(array) {
    return array.map(function(i){ return i; });
}    
function max3(array) {
    return cloneArray(array).sort(function(a,b) { return b-a; }).slice(0,3);
}
function min3(array) {
     return cloneArray(array).sort(function(a,b) { return a-b; }).slice(0,3);
}

var array=scoreByPattern;
alert("Max:"+ max3(array)[0] +' '+max3(array)[1] +' '+max3(array)[2]);
alert("Min:"+ min3(array)[0] +' '+min3(array)[1] +' '+min3(array)[2]);
// Max:98 93 91
// Min:9 17 29

//Top 5 itens
scoreByPattern.sort((a, b) => b - a).slice(0, 5);
// [98, 93, 91, 81, 78]
Javascript ES6 Template strings
const name = 'Matheus'
const message = `Hello `

console.log(message) // prints "Hello Matheus"
Javascript ES6 Destructuring
const Person = {
  name: "John Snow",
  age: 29,
  sex: "male",
  materialStatus: "single",
  address: {
    country: "Westeros",
    state: "The Crownlands",
    city: "Kings Landing",
    pinCode: "500014",
  },
};

const { address : { state, pinCode }, name } = Person;

console.log(name, state, pinCode) // John Snow The Crownlands 500014
console.log(city) // ReferenceErro

//Extract especif information from objects array
let array = [ {"name":"Joe", "age":17, "sex":"M"},{"name":"Bob", "age":17, "sex":"M"},{"name":"Carl", "age": 35, "sex":"M"}];
let especifArrayAtributes = array.map(x => ({firstname: x.name, age : x.age}));
console.log(especifArrayAtributes); //"[{"firstname":"Joe","age":17},{"firstname":"Bob","age":17},{"firstname":"Carl","age":35}]"
Javascript ES6 Rest Parameters
function sum(x, y, z) {
  return x + y + z;
}

const numbers = [1, 2, 3];

console.log(sum(...numbers));
Javascript ES6 Spread Operator
var arr1 = [0, 1, 2];
var arr2 = [3, 4, 5];
arr1.push(...arr2);
console.log(arr1);
Javascript ES6 Array Filter
const allUsers = [{
        "name": "Zediane Araújo",
        "age": 66,
        "picture": "https://randomuser.me/api/portraits/thumb/women/13.jpg",
        "gender": "female"
    },
    {
        "name": "Nara Porto",
        "age": 70,
        "picture": "https://randomuser.me/api/portraits/thumb/women/77.jpg",
        "gender": "female"
    },
    {
        "name": "Ferafina da Cruz",
        "age": 66,
        "picture": "https://randomuser.me/api/portraits/thumb/women/3.jpg",
        "gender": "female"
    },
    {
        "name": "Cliseu Castro",
        "age": 48,
        "picture": "https://randomuser.me/api/portraits/thumb/men/24.jpg",
        "gender": "male"
    },
    {
        "name": "Aiara Cavalcanti",
        "age": 69,
        "picture": "https://randomuser.me/api/portraits/thumb/women/3.jpg",
        "gender": "female"
    }
];

const filteredUsers = allUsers.filter((user) => {
    const inputValue = "CLI"; //Obtenha valor do input com .value, deixei esse valor para exemplo 
    const valueFilterLower = inputValue.toLowerCase(); //convertendo valor do input para minisculo
    const lowername = user.name.toLowerCase(); // converta o nome atual para minisculo
    return lowername.indexOf(valueFilterLower) > -1; // O método indexOf() retorna o primeiro índice em que o elemento pode ser encontrado no array, retorna -1 caso o mesmo não esteja presente.
    //lembrando que O método filter() cria um novo array com todos os elementos que passaram no teste implementado pela função fornecida.
});

console.log(filteredUsers);
Check if video is stopped or playing Javascript only
var video = document.getElementsByTagName("video");
if (video[0].paused) {
    console.log("video is stopped");
    //DO SOMETING...
} else {
    console.log("video is playing");
    //DO SOMETHING...
}

//OR YOU CAN GET video DOM OBJ USING ID
var video = document.getElementById("videoId");
if (video.paused) {
    console.log("video is stopped");
    //DO SOMETING...
} else {
    console.log("video is playing");
    //DO SOMETHING...
}
Videojs check if video is playing
var videoObj = videojs("video_id");

if (!videoObj.paused()) {
    console.log("Video is playing");
} else {
    console.log("Video is paused");
}

//USING .paused() function of videojs
Get first 10 words from string javascript
function getWordStr(str) {
    return str.split(/\s+/).slice(0,10).join(" ");
}

//TO CALL THIS FUNCTION
var fullStr = "We can get first 10 words form this string using the above function";
var finalStr = getWordStr(fullStr);

console.log(finalStr);
xhr post request with form data javascript
var data = new FormData();
data.append('username', 'username');
data.append('email', 'email');

var xhr = new XMLHttpRequest();
xhr.open('POST', 'api_url', true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onload = function () {
    // YOU WILL FIND RESPONSE HERE
    console.log(this.responseText);
};
xhr.send(data);
Remove last character of a string in Javascript
var str = "Hello World";
var finalStr = str.substring(0, str.length-1);
Testest
dsds
test
test
Generate Unique ID
const uuid = (lenght = 10) =>{
    const charts = "abcdefghijklmnopqrstuvwzywABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
    let id = "";
    
    for(let i = 0 ; i < lenght;i++){
        id += charts[Math.floor(Math.random() * charts.length)];
    }
    return id;
}
Password Checker
let passwordChecker = (password) => {
	if (isUpperCase(password) && isLowerCase(password) && isNumber(password) && isProperLength(password) && consOcc(password)){
		return true
	} else {
		return false
	}
}

let consOcc = (password) => {
	let init = password.charAt(0)
	let count = 1
	for (let i=1; i < password.length; i++) {
		if (password.charAt(i) == init) {
			init = password.charAt(i)
			count++
			if (count > 2) {
				return false
			}
		} else {
			init = password.charAt(i)
			count = 1 
		}
	}
	if (count>=3) {
		return false	
	}
	else {
		return true
	}
	// 
}

let isUpperCase = (password) => {
	return /[A-Z]/.test(password)
}

let isLowerCase = (password) => {
	return /[a-z]/.test(password)
}

let isNumber = (password) => {
	return /[0-9]/.test(password)
}

let isProperLength = (password) => {
	if (password.length >= 6 && password.length <= 16) {
		return true;
	}
	return false
}
Promise Chaining
new Promise(function (resolve, reject) {
    setTimeout(() => resolve(1), 1000); // (*)
}).then(function (result) { // (**)
    alert(result); // 1
    return result * 2;
}).then(function (result) { // (***)
    alert(result); // 2
    return result * 2;
}).then(function (result) {
    alert(result); // 4
    return result * 2;
});
Get all child elements of parent element in javascript
var parent = document.getElementById("parent_id");
var childrens = parent.children;
//RETURNS ALL CHILD ELEMENTS HTMLCollection ARRAY
Add new item at first position of array using unshift() method Javascript
var items = ["Apple", "Banana", "Orange"];
items.unshift("Papaya", "Watermelon");
console.log(items);
MAthPix equation
function checkIfEquationExists(str){
    str2 = str.replace(/\["|]/g," ")
    str3 = str2.replace(/[,[]/g," ")
    str4 = str3.replace(/"/g ," ")
    return str4;
}
Loop through object javascript
var items = {
    "item_1": "1",
    "item_2": "2",
    "item_3": "3"
}
for (var item in items) {
    console.log(items[item]);
}
Javascript getAbsolutePath
//Javascript get current url 
function getAbsolutePath() {
    var loc = window.location;
    var pathName = loc.pathname.substring(0, loc.pathname.lastIndexOf('/') + 1);
    return loc.href.substring(0, loc.href.length - ((loc.pathname + loc.search + loc.hash).length - pathName.length));
}
Aerofiler Snippets Javascript
// Aerofiler Search Results Selector 1st column
.ag-header-viewport  .ag-header-container  .ag-header-row:nth-child(1)  .ag-header-cell:nth-child(1)  span.ag-header-cell-text
// Aerofiler Dashboard page - doc activity area- click 1st doc link
document.querySelector("#actTable tbody tr:nth-child(1) a").click()
// Locate and  button using attribute value
document.querySelector("button[data-target='#relatedDocsModal']").click()
document.querySelector("button[data-target='#relatedDocsModal'][data-toggle='modal']").click()
//Search page - get number of doc titles in search results
document.querySelectorAll("div[col-id=title] .wrap").length

//////////////////
//for(count=1;count<=5;count++)
{
  // console.log(document.querySelectorAll("div[role='gridcell'][col-id='startDate']")[count].textContent);
//document.querySelectorAll("div[role='gridcell'][col-id='startDate']")[count].textContent;
}
 // document.querySelectorAll("div[col-id=title] .wrap")[count].innerText;
   //document.querySelectorAll("div[col-id='title'] .wrap")[count].textContent;
//document.querySelectorAll("div[role='gridcell'][col-id='startDate']").textContent

var titles=document.querySelectorAll("div[role='gridcell'][col-id='startDate']");

console.log(titles[1].textContent);
npm module creation/publish
// --  npm module creation
let npmjsAuthCredentials = {
    username : 'purplecrow',
    password : '7600Akshat397973'
}

// -- login using cli

// npm folder  with same name as 
// that in the package & .js file in the package

// npm add user - if needed there for authenticating the 
// user to publish the credentials

// npm version if u want to add new one 
// npm publish
// Note:- Errors - before publishing git tree should be clean
// as without it , the files would not publish.

// -------   -----  for updating the version in the package to be used
//  npm install purplecrow@latest --save


let links = [
'https://stackoverflow.com/questions/15056377/how-do-i-update-an-npm-module-that-i-published#targetText=4%20Answers&targetText=Change%20the%20version%20in%20your,version%20in%20the%20NPM%20repository'
];
Add service worker to your website
//CREATE SERVICE WORKER FILE ON ROOT NAMED AS service-worker.js(Name does not matter)
var cacheName = 'my-web-cache';
var filestoCache = [
    '/css/style.css',
    '/css/main.css',
    '/js/main.js',
    '/images/logo.png'
];

self.addEventListener('install', function(event) {
    event.waitUntil(
      caches.open(cacheName)
        .then(function(cache) {
          console.log('Opened cache');
          return cache.addAll(filestoCache);
        })
    );
});


//CALL SERVICE WORKER FILE AND INSTALL IT(GENERALLY FORM inde.html or other pages)
if ('serviceWorker' in navigator) {
    window.addEventListener('load', function() {
        navigator.serviceWorker.register('/service-worker.js').then(function(registration) {
            console.log('ServiceWorker registration successful with scope: ', registration.scope);
        }, function(err) {
            console.log('ServiceWorker registration failed: ', err);
        });
    });
}
Query selectors in Javascript
//TO SELECT THE VERY FIRST ELEMENT
var element = document.querySelector(".element_class");
//YOU CAN ALSO PASS CHILD HIERARCHY INTO IT
var child_element = document.querySelector(".element_class .child_class");

//TO SELECT ALL ELEMENTS BY CLASS YOU CAN USE BELOW QUERY SELECTOR
var all_elements = document.querySelectorAll(".element_class");

//YOU CAN SLECT ELLEMENTS BY ITS CLASS NAMEs, OR IDs, or BY USING ELEMENTS NAMES LIKE
var all_divs_opn_webpage = document.querySelectorAll("div");
document.addEventListener javascript
document.addEventListener("click", function(){
    console.log("I am clicked")
});

//OR ADD EVENT ON A PARTICULAR EVENT
var button = document.getElementById("button");
button.addEventListener("click", function() {
    console.log("I am clicked on a button");
});
Hide datasets label in Chart.js
var ctx = document.getElementById("mychart").getContext('2d');

var myChart = new Chart(ctx, {
   type: 'line',
   data: {
      labels: ['Point 1', 'Point 2', 'Point 3', 'Point 4'],
      datasets: [{
         labels: "This will be hide",
         data: [20, 50, 40, 30],
         backgroundColor: ["red", "blue", "orange", "green"]
      }]
   },
   options: {
      legend: {
         display: false //This will do the task
      }
   }
});
Create pie chart in Chart.js
var ctx = document.getElementById("pie_chart").getContext('2d');

var myChart = new Chart(ctx, {
   type: 'pie',
   data: {
      labels: ['Point 1', 'Point 2', 'Point 3', 'Point 4'],
      datasets: [{
         labels: "Pie chart",
         data: [20, 50, 40, 30],
         backgroundColor: ["red", "blue", "orange", "green"]
      }]
   }
});
Create line chart in Chart.js
var ctx = document.getElementById("line_chart").getContext('2d');

var myLineChart = new Chart(ctx, {
   type: 'line',
   data: {
      labels: ['Point 1', 'Point 2', 'Point 3', 'Point 4'],
      datasets: [{
         label: "hello",
         data: [40, 50, 80, 20],
         backgroundColor: "rgba(0,0,0,0)",
         borderColor: "#319fe2"
      }]
   },
   options: {
      
   }
});
Create bar chart in Chart.js
var ctx = document.getElementById('myChart').getContext('2d');

var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
       labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple'],
       datasets: [{
            label: '# of Votes',
            data: [90, 60, 50, 50, 100],
            backgroundColor: "#00AAFB",
       }]
    },
    options: {
       scales: {
            xAxes: [{
               gridLines: {
                  display: false
               }
            }],
            yAxes: [{
               ticks: {
                  beginAtZero: true, 
               },
               gridLines: {
                  display: false
               }
            }]
       }
    }
});
Hide gridlines in Chart.js
var ctx = document.getElementById('myChart').getContext('2d');

var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
       labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
       datasets: [{
            label: '# of Votes',
            data: [90, 60, 30, 50, 30, 80],
       }]
    },
    options: {
       scales: {
            xAxes: [{
               gridLines: {
                  display: false
               }
            }],
            yAxes: [{
               gridLines: {
                  display: false
               }
            }]
       }
    }
});
Bar chart with circular shape from corner in Chart.js
Chart.elements.Rectangle.prototype.draw = function() {
    var ctx = this._chart.ctx;
    var vm = this._view;
    var left, right, top, bottom, signX, signY, borderSkipped, radius;
    var borderWidth = vm.borderWidth;
    var cornerRadius = 20;

    if (!vm.horizontal) {
        left = vm.x - vm.width / 2;
        right = vm.x + vm.width / 2;
        top = vm.y;
        bottom = vm.base;
        signX = 1;
        signY = bottom > top? 1: -1;
        borderSkipped = vm.borderSkipped || 'bottom';
    } else {
        left = vm.base;
        right = vm.x;
        top = vm.y - vm.height / 2;
        bottom = vm.y + vm.height / 2;
        signX = right > left? 1: -1;
        signY = 1;
        borderSkipped = vm.borderSkipped || 'left';
    }

    if (borderWidth) {
        var barSize = Math.min(Math.abs(left - right), Math.abs(top - bottom));
        borderWidth = borderWidth > barSize? barSize: borderWidth;
        var halfStroke = borderWidth / 2;
        var borderLeft = left + (borderSkipped !== 'left'? halfStroke * signX: 0);
        var borderRight = right + (borderSkipped !== 'right'? -halfStroke * signX: 0);
        var borderTop = top + (borderSkipped !== 'top'? halfStroke * signY: 0);
        var borderBottom = bottom + (borderSkipped !== 'bottom'? -halfStroke * signY: 0);
        if (borderLeft !== borderRight) {
            top = borderTop;
            bottom = borderBottom;
        }
        if (borderTop !== borderBottom) {
            left = borderLeft;
            right = borderRight;
        }
    }

    ctx.beginPath();
    ctx.fillStyle = vm.backgroundColor;
    ctx.strokeStyle = vm.borderColor;
    ctx.lineWidth = borderWidth;
    var corners = [
        [left, bottom],
        [left, top],
        [right, top],
        [right, bottom]
    ];

    var borders = ['bottom', 'left', 'top', 'right'];
    var startCorner = borders.indexOf(borderSkipped, 0);
    if (startCorner === -1) {
        startCorner = 0;
    }

    function cornerAt(index) {
        return corners[(startCorner + index) % 4];
    }

    var corner = cornerAt(0);
    ctx.moveTo(corner[0], corner[1]);

    for (var i = 1; i < 4; i++) {
        corner = cornerAt(i);
        nextCornerId = i+1;
        if(nextCornerId == 4){
            nextCornerId = 0
        }

        nextCorner = cornerAt(nextCornerId);

        width = corners[2][0] - corners[1][0];
        height = corners[0][1] - corners[1][1];
        x = corners[1][0];
        y = corners[1][1];
        
        var radius = cornerRadius;
        
        if(radius > height/2){
            radius = height/2;
        }if(radius > width/2){
            radius = width/2;
        }

        ctx.moveTo(x + radius, y);
        ctx.lineTo(x + width - radius, y);
        ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
        ctx.lineTo(x + width, y + height - radius);
        ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
        ctx.lineTo(x + radius, y + height);
        ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
        ctx.lineTo(x, y + radius);
        ctx.quadraticCurveTo(x, y, x + radius, y);
    }

    ctx.fill();
    if (borderWidth) {
        ctx.stroke();
    }
}; 

//NOW DRAW YOUR CHART
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
       labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
       datasets: [{
            label: '# of Votes',
            data: [90, 60, 30, 50, 30, 80],
            borderWidth: 0,
            backgroundColor: "#00AAFB",
       }]
    },
    options: {
       scales: {
            xAxes: [{
               barThickness: 15,
            }],
            yAxes: [{
               ticks: {
                  beginAtZero: true
               }
            }]
       }
    }
});
Basic server configuration in Nodejs
const http = require('http');
const app = require('./app');
const port = process.env.PORT || 3500;



const server = http.createServer(app);

server.listen(port);
CORS Headers in Nodejs
app.use((req,res,next)=>{
    res.header('Access-Control-Allow-Origin','*');
    res.header(
        'Access-Control-Allow-Header',
        'Origin,X-Resquested-With,Content-Type,Accept,Authorization'
        );
    if(req.method === 'OPTIONS'){
        res.header(
            'Access-Control-Allow-Methods',
            'GET,POST,PUT,PATCH,DELETE'
            );
        return res.status(200).json({});
    }
    next();
});
indexOf and lastIndexOf a string in javascript
var str = "Check where grapes found";
str.indexOf("grapes"); //It will return 12 as the index

var str = "grapes are not grapes until found";
str.lastIndexOf("grapes"); // Return last index of 'grapes' in str var
JavascriptFirst
var str = "Welcome Developer";
console.log(str);
Get Pseudo elements using Javascript
var elem = window.getComputedStyle(document.querySelector('.element'), ':before');
elem.getPropertyValue('color');
Create random string in Javascript
Math.random().toString(36).substring(2, 15)
Add class to an element in javascript
var element = document.getElementById("element_id");
element.classList.add("className"); // ADD CLASS TO ELEMENT

element.classList.remove("className"); //REMOVE CLASS FROM ELEMENT
Create form data in Javascript
var form = document.getElementsByTagName("form")[0];
var formData = new FormData(form);

formData.get("title"); //TO GET A KEY(KEY NAME WILL BE name attribute defined in your input controls)
formData.set("title", "This is new title"); //TO SET NEW VALUE TO A KEY

formData.delete("about"); //TO DELETE A KEY FROM FORM DATA
Sort array using Array.sort() in javascript
//SORT ARRAY ALPHABETICALLY
var arr = ["Joe", "Victor", "Henna"];
arr.sort();
arr.reverse(); //DESCENDING ORDER

//SORT ARRAY NUMERICALLY
var numeric_arr = [50, 20, 40, 60, 10, 30];
numeric_arr.sort(function(a, b) { return a - b }); //ASCENDING ORDER
numeric_arr.sort(function(a, b) { return b - a }); //DESCENDING ORDER

//Array of Objects
var fruits = [
    { 'name': 'banana', 'color': 'yellow' },
    { 'name': 'apple', 'color': 'red' },
    { 'name': 'orange', 'color': 'orange' }
];
//SORT ARRAY OF OBJECT
fruits.sort(function (a, b) { return a.name.localeCompare(b.name) });
console.log(fruits);
Replace characters globally Javascript
//Case sensitive
var str = "Color is Green and green is a cold color";
var result = str.replace(/green/g, "blue");
//output - Color is Green and blue is a cold color

//Applly for case insensitive
var res = str.replace(/green/gi, "blue");
//output - Color is blue and blue is a cold colors
Random & Unique CSS Gradient-Color Generator
// HTML CODE
// <h1>Welcome to the game!</h1>
//   <input type="text" name="number" id="" onkeyup="generate(this)"
//      placeholder="Enter your favourite number and then press TAB">
// <div id="result">

let generate = (ele) => {
    if (!isNaN(ele.value)) {
        document.getElementById("result").innerHTML = "";
        // alert(ele.value);
        let letters = "0123456789ABCDEF";
        array_1 = [];
        array_2 = [];
        for (i = 0; i < ele.value; i++) {
            let color_1 = '#';
            let color_2 = '#';
            do {
                for (let i = 0; i < 6; i++) {
                    color_1 += letters[(Math.floor(Math.random() * 16))];
                    color_2 += letters[(Math.floor(Math.random() * 16))];
                }
                array_1.push(color_1);
                array_2.push(color_2);
            } while (!array_1.includes(color_1) && array_2.includes(color_2));
            let div = document.createElement("div");
            div.style.width = "200px";
            div.style.height = "200px";
            div.style.backgroundImage = "linear-gradient(to right," + color_1 + "," + color_2 + ")";
            div.style.color = "white";
            div.style.display = "inline-flex";
            div.style.margin = "25px";
            document.getElementById("result").appendChild(div);
        }
        array_1 = [];
        array_2 = [];
    } else {
        alert("Only Number is allowed");
        document.getElementById("result").innerHTML = "";
    }
}
Super awesome snipper
import patientReducer from '../reducers/patientReducer';
 import joinMultipleApiResponse from '../utils/joinMultipleApiResponse';
 
-const initialState = {};
Array.forEach() in javascript
var myarray = ['1', '2', '3'];

myarray.forEach(function(item, index) {
    console.log("item is : ", item, ", index is : ", index)
});
Convert all characters to lowercase using toLowerCase() method in javascript
var str = "World Is Beautiful";
console.log(str.toLowerCase());