Skip to content
Advertisement

I want to replace this forEach function with the same but done using reduce. Can you say where I am doing wrong?

I create the columns and I have a checkbox which shows the columns name. When I click a checkbox square I get an array of checked names which are stored in checkedKeys. Now checkableColumns contains all the possible checkable values. Those elements which are in checkableColumns but not in checkedKeys are those columns that will disappear from the table’s columns. I don’t filter from all columns because some columns should always be visible. This is common part to reduce and forEach:

const columns = initColumns();
        const checkableColumns = ["n", "yi", "ui", "r", "t"];
        const notCheckedValues = checkableColumns.filter(col=>!checkedKeys.includes(col));
        const filteredColumns =[];

Here how I solved with forEach:

columns.forEach(column=>{
      if(!notCheckedValues.includes(column.dataIndex)){
            filteredColumns.push(column);
          }
    })

Here how I tried to solve with reduce, but it doesn’t work and I didn’t understand:

const filteredColumns = columns.reduce((allColumns, currentColumn)=>{
      if(notCheckedValues.includes(currentColumn.dataIndex)){
        return allColumns;
      }
      console.log("all cols",allColumns, "push",allColumns.push(currentColumn))
      return allColumns.push(currentColumn)
    }, [])

Advertisement

Answer

Array.prototype.push does not return the Array, but the new length of the array: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push

Instead, you would need to return the accumulator after pushing:

const filteredColumns = columns.reduce((allColumns, currentColumn) => {
  if (notCheckedValues.includes(currentColumn.dataIndex)) {
    return allColumns;
  }
  allColumns.push(currentColumn)
  return allColumns
}, [])

You could however also do this in a more idiomatic way by using Array.prototype.filter: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

const filteredColumns = columns.filter((currentColumn) => {
  return !notCheckedValues.includes(currentColumn.dataIndex)
})
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement