Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding how reduce can be used instead of map and join in this function

I've got the following function that gets all checked checkboxes on my html form with the given element Name. I have a loose understanding that a reduce function can replace the .map and .join sections so was looking for a poke in the right direction of how to implement that and also if there is any other steps I could take to optimise this function?

  function getCheckedValuesOf(elmName){
    return [...document.getElementsByName(elmName)].filter(box=>box.checked==true).map(box=>box.value).join(", ")
  }
like image 223
Gavin Hanel Avatar asked Mar 03 '23 04:03

Gavin Hanel


2 Answers

function getCheckedValuesOf(elmName) {
  return [...document.getElementsByName(elmName)]
    // acc is value returned by previous iteration
    // curr is the current iterated element
    .reduce((acc, curr) => {
      // do nothing on unchecked
      if (curr.checked) {
        // add a , only if acc is not empty, to prevent useless starting ,
        acc += (acc !== "" ? ", " : "") + curr.value
      }
      
      // always return acc, or next iteration will have acc === undefined
      return acc;
      
    // second argument of reduce is the initial value of acc
    // if not set then it default to the first element of the array
    // and the iteration starts on the second element
    }, '')
}

document.getElementById("log").onclick = () => console.log(getCheckedValuesOf("name"))
console.log(getCheckedValuesOf("name"))
<input type="checkbox" name="name" checked="false" value="i1"/>i1
<input type="checkbox" name="name" value="i2"/>i2
<input type="checkbox" name="name" checked="false" value="i3"/>i3
<input type="checkbox" name="name" value="i4"/>i4
<input type="checkbox" name="name" checked="false" value="i5"/>i5
<input type="checkbox" name="name" value="i6"/>i6

<button id="log">log</button>
like image 63
jonatjano Avatar answered Mar 05 '23 16:03

jonatjano


Can you try this one? Let me know if it works.

function getCheckedValuesOf(elmName) {
    return [...document.getElementsByName(elmName)].reduce((a, b) => b.checked && b.value && (a.length>0 ? `${a}, ${b.value}`: `${a} ${b.value}`) || a, "");
}
like image 34
Akshay Bande Avatar answered Mar 05 '23 15:03

Akshay Bande