Writing clean code when working with non-mutating methods

The code below works fine but Im’ wondering about how clean it is to use construction such as array = array... Indeed should I just create another variable or is that ok as is? Since I’m not altering the arguments passed in, I think that should be ok but I’m a noob!

Love it though (learning coding, not being a noob :wink:

My code so far

function uniteUnique(arr) {
  let array = [];
  for (let obj in arguments) {
    array = array.concat(arguments[obj])
  }
  array = array.filter((x,y) => !array.slice(0,y).includes(x))
  return array;
}

Challenge: Sorted Union

Link to the challenge:

1 Like

Hi @Gjloss,

It is dangerous to implement mutation methods in some cases, but in simple cases, mutations are absolutely fine. For example, I don’t see a reason why you cannot push all the arguments to the array and then use this array to filter the data with instant return :slight_smile:

function uniteUnique() {
  const array = [];
  for (let obj in arguments) {
    array.push(arguments[obj])
  }
  return array.filter((x,y) => !array.slice(0,y).includes(x))
}

// or

function uniteUnique() {
  return Object.values(arguments).filter((x,y) => !array.slice(0,y).includes(x))
}
2 Likes

Actually, array = array.concat(...) is a non-mutating operation - .concat() returns a new array each time, and the variable inside this function simply points to a new memory location each time, leaving the original reference untouched.

The push method is mutating, but you’re right - it’s only mutating the local (new) array. However, simply pushing each argument into the array isn’t going to do it, as arguments contains a series of arrays. You either need to expand each argument (like array.push(...arguments[obj]) ) or use concat and join array to array.

2 Likes