8000 add explanation and simpler solution to removeFromArray · M-Munk/javascript-exercises@c0ef28a · GitHub
[go: up one dir, main page]

Skip to content

Commit c0ef28a

Browse files
committed
add explanation and simpler solution to removeFromArray
1 parent a70a250 commit c0ef28a

File tree

1 file changed

+31
-5
lines changed

1 file changed

+31
-5
lines changed

removeFromArray/removeFromArray.js

Lines changed: 31 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,32 @@
1-
var removeFromArray = function(...args) {
2-
const array = args[0]
3-
return array.filter(val => !args.includes(val))
4-
}
1+
// we have 2 solutions here, an easier one and a more advanced one.
2+
// The easiest way to get an array of all of the arguments that are passed to a function
3+
// is using the spread operator. If this is unfamiliar to you look it up!
4+
const removeFromArray = function (...args) {
5+
// the very first item in our list of arguments is the array, we pull it out with args[0]
6+
const array = args[0];
7+
// create a new empty array
8+
const newArray = [];
9+
// use forEach to go through the array
10+
array.forEach((item) => {
11+
// push every element into the new array
12+
// UNLESS it is included in the function arguments
13+
// so we create a new array with every item, except those that should be removed
14+
if (!args.includes(item)) {
15+
newArray.push(item);
16+
}
17+
});
18+
// and return that array
19+
return newArray;
20+
};
521

6-
module.exports = removeFromArray
22+
23+
// A simpler, but more advanced way to do it is to use the 'filter' function,
24+
// which basically does what we did with the forEach above.
25+
26+
// var removeFromArray = function(...args) {
27+
// const array = args[0]
28+
// return array.filter(val => !args.includes(val))
29+
// }
30+
//
31+
32+
module.exports = removeFromArray;

0 commit comments

Comments
 (0)
0