I am new to javascript and I am having a bit of challenge learning it myself from web tutorials. Please help me to solve the problem below.
Problem:
Write a function that takes two or more arrays and returns a new array of unique values in the order of the original provided arrays.
In other words, all values present from all arrays should be included in their original order, but with no duplicates in the final array.
The unique numbers should be sorted by their original order, but the final array should not be sorted in numerical order.
Use only Array.reduce to solve this ! This is what your solution should look like:
function unite(arr1, arr2, arr3) {
return arr1;
}
unite([1, 2, 3], [5, 2, 1, 4], [2, 1]);
I am not able to understand how I can use reduce here. All the internet examples are so easy compared to this. https://www.airpair.com/javascript/javascript-array-reduce http://adripofjavascript.com/blog/drips/boiling-down-arrays-with-array-reduce.html
My wrong solution:
function arrayDiff(resultArray, element){
var idx = anotherArray.indexOf(element);
if(idx != -1){
resultArray.push(element);
return resultArray;
}
}
function unite(arr1, arr2, arr3) {
var arr = [];
var r1 = arr1.reduce(arrayDiff);
var r2 = arr2.reduce(arrayDiff);
var r3 = arr3.reduce(arrayDiff);
arr.concat(r1).concat(r2).concat(r3);
return arr;
}
r = unite([1, 2, 3], [5, 2, 1, 4], [2, 1]);
console.log(r);
Error: ReferenceError: anotherArray is not defined
anotherArrayis not defined. What that variable is supposed to refer at?anotherArrayis not defined. What did you expect it to be?var sum = [1, 2, 3].reduce( function(total, num){ return total + num }, 0);. Looks like total is the result variable. So, I followed that example and made anotherArray as my result variable. This is confusing.totalis the first argument.