Apr 20, 2018

Javascript / Jquery working with arrays

When accessing jquery selector that returns list of elements you can't access elements using standard array methods:
- find
- map
- filter
Use only JQuery each.

var getCheckedInputIdList = function () {
        var checked = $('#map input.mapFilterControl[type="checkbox"]:checked');
        var checkedIdList = [];
        checked.each(function () {
            var filterItemValue = $(this)[0].id;
            checkedIdList.push(filterItemValue);
        });
        return checkedIdList;
    }


    var doesExistForId = function (arr, findThis) {
        return arr.find(function (element) {
            return element && element.Id === findThis.Id;
        })
    }


Short-hand or Arrow functions ( C# lambda like)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Warning! Arrow functions don't support "this" or constructors ?

Reduce, Slice & Join in Action

"You are given an array strarr of strings and an integer k. Your task is to return the first longest string consisting of k consecutive strings taken in the array.

#Example: longest_consec(["zone", "abigail", "theta", "form", "libe", "zas", "theta", "abigail"], 2) --> "abigailtheta"

n being the length of the string array, if n = 0 or k > n or k <= 0 return ""."
function longestConsec(strarr, k) {   
    return strarr.length > 0 && strarr.length >= k && k > 0
      ? strarr.reduce((longest, item, i) => {
        var curr = strarr.slice(i, i + k).join('');
          return curr.length > longest.length ? curr : longest;
           }, strarr.slice(0,k).join(''))
      : "";   
}
console.log( longestConsec(["wlwsasphmxx","owiaxujylentrklctozmymu","wpgozvxxiu"], 2) ); 

Reduce must produce single result. Watch for initial value for acumulator! In above sample we had to explicitly calculate it by joining k elements. By default it will take myArray[0] for acumulator value. 
Use it to iterate and calculate single result. Note how you don't have to care for "index out of range". Example shows how you iterate using reduce and again using slice inside on same array.

Slice DOESN'T take second index so for ...slice(0,1) you'll get only element[0] !

Join without params like this Join() will use ',' as delimiter. Use explicit Join('') for empty delimiter.