CSX Challenge Solution: union (CSX Callbacks & Higher Order Functions Unit)

preview_player
Показать описание


Stay connected to the Codesmith community!

Follow Codesmith to stay updated!
Рекомендации по теме
Комментарии
Автор

well, i did it like this in a simple way also it checks the first array before move on to second cuz there maybe duplicates in the first array
function union(arrays) {
const newArray = [];
for(let i = 0; i < arrays.length; i++) {
arrays[i].forEach(element => {
{
newArray.push(element);
}
});
}
return newArray;
}

anyway thank you Casey for the video !!

monkeymediatv
Автор

In this code, I noticed that if the first array has duplicates, it will not check for it. I made a workaround shown here:

function union(arrays) {
//Difference in code is shown in this block to check and replace the first array to an array without any repeats.
const replaceArray = []
arrays[0].forEach((el) => {
replaceArray.push(el);
});
arrays[0] = replaceArray;


return arrays.reduce((acc, currVal) => {
currVal.forEach((el) => {
if(!acc.includes(el)) acc.push(el)
})
return acc;
});
}

stevenmonstop
Автор

figured out a very dry method for this
function union (arrays){
return Array.from((new Set(arrays.flat(Infinity))))

}

jenmorgan
Автор

Hi all members of CodeSmith thank you very much for all your effort to pass the information to us i see some course of will sentance i love this men by his explication of the cours in JavaScript the hard part so i do some research in google and i found your site codeSmith and i'm here now in your channel youtube, i have some question : you do each week live on youtube or on codesmith ? and can we interact and i ask about the live for free ? please some explication how you work and how can i follow you ?

mahdisoultana
Автор

My solution:

function union(arrOfArrays) {
return arrOfArrays.reduce((acc, curr) => {
return => !acc.includes(element)));
}, []);
}

kodyn
Автор

The presented solution works great as a learning tool. But it could be refactored to optimize for time complexity. Presented solution is at O(n^3) since the nested includes() method has O(n) complexity. Here's my refactored solution at O(n^2) leveraging Set and Array constructors to avoid those triply nested linear operations:

const union = arrays => arrays.reduce( (acc, next) => Array.from(new Set( [...acc, ...next] ) ) ) ;

Of if you prefer the logic across several lines:

const union = arrays => arrays.reduce( (acc, next) => {
Array.from(new Set( [...acc, ...next] ) )
});

Nick-tsqc
Автор

Initially I wanted to reach for a set, but went with this instead:

function union(arrays) {
const result = [];

arrays.forEach(arr => {
result.push(...arr);
})

return result.reduce((acc, curr) => {
if (!acc.includes(curr)) acc.push(curr);
return acc;
}, []);
}

joel_bio
Автор

I don't think you need to add the initial value to the reduce method because the first array element will already contain only unique values.

PatrickSullivanJ
join shbcf.ru