We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
console.log(// A JavaScript Set only allows distinct entries so we avoid duplicates.// Also, converting to lowercase means we can ignore case when doing matching.newSet(input.toLowerCase()// Split input by newline.split('\n')// Extract a subarray which ignores index 0: each line = one rock.slice(1)// For each rock, convert to an array of elements.map(rock=>rock.split(''))// Now an array of arrays [ [ 'A', 'B' ], [ 'C', 'D' ] ]// Iterate through all 'inner' arrays in 'outer' array.// For each 'inner' array we will create a new array which contains only those items which are in both the current and previous 'inner' arrays.// This new array becomes the input for the next iteration.// See function breakout below....reduce(keepOnlyItemsWhichAreInBothArrays)// Return the size of the new Set. We know each element will only be counted once because they're all lowercase and Set only allows distinct entries).size);// Reduce function//// Walkthrough://// for array [ // [ 'A', 'B' ], // [ 'B', 'C' ], // [ 'B', 'E' ] // ]// Iteration 1 compares: [ 'A', 'B' ], [ 'B', 'C' ]// Iteration 1 results in new array [ 'B' ]// Iteration 2 compares: [ 'B' ], [ 'B', 'E' ]// Iteration 2 results in new array [ 'B' ]// Function returns [ 'B' ]functionkeepOnlyItemsWhichAreInBothArrays(prev,curr){// Returns true if 'element' is in 'prev'.functionisInPreviousArray(element){returnprev.includes(element);}// Create new array out of items which return true for the function above.returncurr.filter(isInPreviousArray);}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Gemstones
You are viewing a single comment's thread. Return to all comments →
Sure: