Reduce and filter refusing to co-operate!

As a newbie, I’m trying to use iterative methods like reduce and filter, in order to get familiar with their operation.

Using both with Sorted Union (Intermediate Algorithms), I can’t spot why my code is failing to work.

I’m guessing some simple-level mistake here, but can’t see it. So could use a bit of help from more experienced coders.

My code:

function uniteUnique(arr) {
 let newArr = [...(arr)]  //create new, flattened arr
     .reduce(function(accum, currVal) {
     return accum.concat(currVal)
   }, [] );
   
var resultArr = newArr //filter out repeated values  
   .filter(function(item, pos) {
     return newArr.indexOf(item) == pos;
   });
   
   return resultArr;

}
uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.106 Safari/537.36.

Challenge: Sorted Union

Link to the challenge:

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

Please use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks are not single quotes.

markdown_Forums

Hello~!

Take a look at what your functions are doing - it looks like they only access the first sub-array:

Hi

Thanks, I’ll get onto it now.

Yes, you’re right.

Back to the drawing board…

Many thanks,

PeterL

Changed first line to

let newArr = Array.from(arguments) //the rest I left intact

Worked beautifully!

I had tried a similar first line earlier, but for some reason it didn’t produce the goods.

I find this new field of study to be fiendishly awkward, especially because, when checking code, one can not be sure which elements of the code are going wrong, from a simple syntax error, to a more abstruse misunderstanding of (nested) functions/methods, and the like.

As a linguist (in an earlier life) , it’s a bit like learning 3 languages at once, then combining them.

Your help is much appreciated!

PeterL

1 Like