Sunday, 11 August 2019

Array methods tips and tricks



  1. shift and unshiftarr.shift() – extracts an item from the beginning,
    arr.unshift(...items) – adds items to the beginning.
  2. splice: 
    The arr.splice(str) method is a swiss army knife for arrays. It can do everything: insert, remove and replace elements.
    arr.splice(index[, deleteCount, elem1, ..., elemN])
  3. thisArg:
    Almost all array methods that call functions – like find, filter, map, with a notable exception of sort, accept an optional additional parameter thisArg.
    arr.find(func, thisArg);
    arr.filter(func, thisArg);
    arr.map(func, thisArg);
    // ...
    // thisArg is the optional last argument
    The value of thisArg parameter becomes this for func.
  4. concat:arr.concat(arg1, arg2...)
    argN: not always an array
    If an argument argN is an array, then all its elements are copied. Otherwise, the argument itself is copied.
    Eg:
    let arr = [1, 2];
    alert( arr.concat([3, 4])); // 1,2,3,4
    alert( arr.concat([3, 4], [5, 6])); // 1,2,3,4,5,6
    alert( arr.concat([3, 4], 5, 6)); // 1,2,3,4,5,6 //one arg is an array, rest two are numbers

  5. Sort numeric arraylet arr = [ 1, 2, 15 ];
    // the method reorders the content of arr
    arr.sort();
    alert( arr );  // 1, 15, 2
    Solution: Pass a comparison function as the first argument to sort function.
    Eg: arr.sort(function(a, b) { return a - b; });




src: http://javascript.info/array-methods

No comments:

Post a Comment