Trace the fixed program
Three local rows contain A, B and C. Keep only visible rows, then lowercase their IDs for display. B remains in the source even though it is absent from display.
const source=[{id:'A',visible:true},{id:'B',visible:false},{id:'C',visible:true}];
const display=source.filter(row=>row.visible).map(row=>row.id.toLowerCase());
console.log(JSON.stringify({display,sourceIds:source.map(row=>row.id)}));
{"display":["a","c"],"sourceIds":["A","B","C"]}| Stage | IDs | Effect on source |
|---|---|---|
| Source | A, B, C | length: 3 |
| filter | A, C | B omitted from result only |
| map | a, c | Returns strings |
Explain the result
filter creates a new array of selected values; map creates a new array from callback results. These callbacks only read source objects and return strings. A filtered array of objects still shares those objects, and callbacks can mutate them if written that way.
Test the alternative
Changing an object through the filtered result changes the original object. A new array does not mean new records.
const source=[{id:'A',visible:true},{id:'B',visible:false}];const filtered=source.filter(row=>row.visible);
filtered[0].id='Changed';
console.log(JSON.stringify({differentArray:filtered!==source,sameRow:filtered[0]===source[0],sourceIds:source.map(row=>row.id)}));
{"differentArray":true,"sameRow":true,"sourceIds":["Changed","B"]}Work the boundary case
If no row is visible, does filter delete anything from source?
Show the worked answer
No. It returns an empty result array. The original rows and their order remain.
const source=[{id:'A',visible:false},{id:'B',visible:false}];const display=source.filter(row=>row.visible).map(row=>row.id.toLowerCase());
console.log(JSON.stringify({display,sourceIds:source.map(row=>row.id),length:source.length}));
{"display":[],"sourceIds":["A","B"],"length":2}