Skip to content

Instantly share code, notes, and snippets.

@rimivan
Last active January 12, 2021 17:19
Show Gist options
  • Save rimivan/d20832380c705fb2290b71885dba3917 to your computer and use it in GitHub Desktop.
Save rimivan/d20832380c705fb2290b71885dba3917 to your computer and use it in GitHub Desktop.
Simple ES6 reference with useful methods
const orders = [500, 30, 99, 15, 223];
/**
* Reduce
* @return a single value as output
*/
const total = orders.reduce((acc, cur) => acc + cur)
/**
* Map
* @return an array as output
*/
const withTax = orders.map(v => v * 1.1)
/**
* Filter
* @return an array as output
*/
const highValue = orders.filter(v => v > 100);
/**
* Every
* @return a single boolean output
*/
const everyValueGreaterThan50 = orders.every(v => v > 50)
const everyValueGreaterThan10 = orders.every(v => v > 10)
/**
* Some
* @return a single boolean output
*/
const someValueGreaterThan500 = orders.some(v => v > 500)
/**
* Some
* @returns true
*/
const someValueGreaterThan10 = orders.some(v => v > 10)
/**
* Variable Evaluation
* Reference:
* https://stackoverflow.com/questions/2647867/how-can-i-determine-if-a-variable-is-undefined-or-null
*/
if (typeof EmpName != 'undefined' && EmpName) {
/* will evaluate to true if value is not:
null
undefined
NaN
empty string ("")
0
false
*/
/**
* Remove duplicate from array
* Reference:
* https://stackoverflow.com/questions/2647867/how-can-i-determine-if-a-variable-is-undefined-or-null
*/
//from simple array
var arr = [1,2,3,4,5,1,1,2];
const remDuplicateWithSet = (data) => {
return [...new Set(data)]
}
console.log(remDuplicateWithSet(arr));
// from array of objects
var arrayObj = [
{
'id':'1',
'name':'iri1',
},
{
'id':'2',
'name':'iri2',
},
{
'id':'3',
'name':'iri3',
},
{
'id':'1',
'name':'iri1',
},
{
'id':'3',
'name':'iri1',
},
{
'id':'3',
'name':'iri1',
},
];
function removeDuplicates(array, key) {
return array.filter((obj, index, self) =>
index === self.findIndex((el) => (
el[key] === obj[key]
))
)
}
console.log(removeDuplicates(arrayObj, 'id'))
/**
* Add and remove elements on arrays
*/
addAndRemove() {
    let A = [
      {
        id1,
      },
      {
        id2,
      },
      {
        id3,
      },
    ];
    const B = [
      {
        id1,
      },
      {
        id4,
      },
      {
        id5,
      },
    ];
    // add
    B.forEach((obj) => {
      if (
        !A.find((x) => {
          return x.id == obj.id;
        })
      ) {
        A.push(obj);
      }
    });
    // remove
    A.forEach((obj, index, array) => {
      if (
        !B.find((x) => {
          return x.id == obj.id;
        })
      ) {
        array.splice(index, 1);
      }
    });
  }
/**
* Some References:
* Array Docs: https://www.tutorialspoint.com/es6/es6_arrays.htm
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment