Reference Filter

  • Creates a new array with filtered contents, this is a shallow copy.
  • BUT it still references the original sauce so if you remove/mutate items from the filtered or original it will effect both
  • This can be combatted by creating a copy without references: const newArr = [...origArr]
  • W3Schools Documentation Array Filter

Number of Todos before pop = 200 (notice how the pop actually removes 1 item from total and Incompeleted)
Number of Todos in total = 200
Number of compeleted Todos = 90
Number of Incompeleted Todos = 110
WDS Video on Array Methods
fetch("https://jsonplaceholder.typicode.com/todos") .then((response) => response.json()) .then((todos) => { const arrFilter = { total: 0, completed: 0, incomplete: 0 }; arrFilter.total = todos.length; arrFilter.completed = todos.filter((t) => t.completed).length; arrFilter.incomplete = todos.filter((t) => !t.completed).length; todos.pop(); console.log(todos, arrFilter); }); // Example where you creating a new reference point const arr1 = [{ fname: "123" }, { fname: "124" }, { fname: "125" }]; // arry1 now contains pointers to the three objects. // eg. arr1[0] = 0x123, arr1[1] = 0x124, arr1[2] = 0x125 // arr1[0].fname references the fname property of the object stored at 0x123 const arr2 = arr1.filter((a, i) => i < 1); // arry2 now contains pointers to the just the object 0x123 // eg. arr2[0] = 0x123 // arr2[0].fname also references the fname property of the object stored at 0x123 arr1[0] = { fname: "126" }; // eg. arr1[0] = 0x126, arr1[1] = 0x124, arr1[2] = 0x125 // arr2[0].fname noww references the fname property of the object stored at 0x126 console.log(arr1[0].fname, arr2[0].fname); // ddd aaa // Example of Mutating reference so effects both copies of the array const people = [{ name: "David" },{ name: "Justin" },{ name: "Paul" },{ name: "John" },]; const peopleNotJohn = people.filter((person) => person.name !== "John"); console.log(people[0].name, peopleNotJohn[0].name); //David people[0].name = "Fred"; console.log(people, peopleNotJohn); //Fred