javascript - How can I find all arrays with the same values? -
i have array several arrays inside him, that:
var arrs = [ ['qqq', 5], ['www', 2], ['qqq', 15], ['qqq', 11], ['www', 1], ['eee', 22] ]; how can find arrays same values , sum them 1 array, that:
[ ['qqq', 31], ['www', 3] ]; any appreciated!
you should use new "results" array store output. loop input array , either add results (if new one), or update results if match found.
something this:
var arrs = [ ['qqq', 5], ['www', 2], ['qqq', 15], ['qqq', 11], ['www', 1], ['eee', 22] ]; function sumduplicates(arr) { var results = [];//array hold results //loop input array can process each item (var = 0; < arr.length; i++) { var current = arr[i];//get current item processing var match = null;//this hold match, if find 1 //loop results existing match (var j = 0; j < results.length; j++) { var item = results[j];//get item in results want check match //check if have found match if (item[0] === current[0]) { match = item;//match found store match later break;//match found break loop } } //no match found, add current item results (so can matched later) if (!match) results.push(current); //match found, increment stored value else match[1] = match[1] + current[1]; } return results; } var result = sumduplicates(arrs); console.log(result); note include non-duplicates (such 'eee'), makes sense me. if reason need remove items without duplicates let me know
Comments
Post a Comment