Posts

Find matched object in es6

How to get matched id object or other value?  const arr = [{'id': 1, ‘name’: ‘abc’'},{'id': 5,  ‘name':'xyz'}]; const result = arr.find((v) => v.id === 5); if we want an array of matching elements: const result = arr.filter((v) => v.id === 5); The find() method returns the first value in the array, if an element in the array satisfies the provided testing function. Otherwise return undefined.

Elements position in JavaScript

  getBoundingClientRect() is a javascript function that returns the position of the element relative to viewport of window. const position = selector.getBoundingClientRect(); const result = position.top + window.scrollY;

Break loop once condition match JavaScript

const arr = [1,2,3];  Iterations loops: for  every()  some() We can use: for(let item of arr){   console.log(item);  if(item == 2){      break;   }  } Or for (var i = 0; i < arr.length; i++) {   console.log(arr[i]);   if (arr[i] === 2) {        break;   }  } Or arr.every((elm) => {   console.log(elem);   if (elm === 2) {        return true;  }  return false; }); Or  arr.every((elm) => {   console.log(elem);   if (elm === 2) {        return false;  }  return true;  });

How to check variable is an array es6

const arr = [1,5,7]; const result = arr.constructor === Array;  const result = Array.isArray(arr);  Or in Lodash:  const result =  _.isArray(arr); note: typeof []; // returns 'object' and arr.length check will fail if variable is a string.

How to remove last character from string value?

How to remove last character from string value? const val = "11.125";  const result = val.slice(0, -1); Or const result = val.substring(0, val.length - 1); Only if we need numeric value and ristrict decimal value two digit for above case  let numb = parseFloat(val); numb = numb.toFixed(2);

Window height detect es6

const result  = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight; Or const result = window.screen.availHeight; Or const result = window.innerHeight; in jquery :  $(window).height(); // Full height of the HTML page, including content   $(document).height(); // document's viewport height

How to iterate object key/values es6

How to iterate object key/values? const obj = { a: "foo", b: "bar" }; const result = Object.keys(obj).forEach((key,i) => {    // ..  });