Algorithm 202: Array Merging Without Duplicates in 4 Ways
NJOKU SAMSON EBERE
Posted on March 19, 2020
When given a number of arrays, in how many ways can you merge the arrays without duplicates? I have 4 ways prepared for you!
mergeArrays([1, 2, 3, 3, 3], [1, 4, 5, 3, 2], [1, 4, 8, 9])
// [ 1, 2, 3, 4, 5, 8, 9 ]
mergeArrays(["Enugu", "Abia", "Lagos"], ["Lagos", "Sokoto", "Enugu"])
// [ 'Enugu', 'Abia', 'Lagos', 'Sokoto' ]
Prerequisite
To benefit from this article, you need to have basic understanding of javascript's array methods.
Let's do this using:
- for...of...loop, spread operator, includes(), push(), forEach()
function mergeArrays(...arrays) {
let combineArray = [];
let finalArray = [];
for (array of arrays) {
combineArray = [...combineArray, ...array];
}
combineArray.forEach(element => {
if (!finalArray.includes(element)) {
finalArray.push(element);
}
});
return finalArray;
}
- for...of...loop, spread operator, includes(), push(), Array.from()
function mergeArrays() {
let givenArray = Array.from(arguments);
let combineArray = [];
let finalArray = [];
for (array of givenArray) {
combineArray = [...combineArray, ...array];
}
for (element of combineArray) {
if (!finalArray.includes(element)) {
finalArray.push(element);
}
}
return finalArray;
}
- for...of...loop, spread operator, Set()
function mergeArrays(...arrays) {
let combineArray = [];
let finalArray = [];
for (array of arrays) {
combineArray = [...combineArray, ...array];
}
finalArray = [...new Set([...combineArray])];
return finalArray;
}
- for...of...loop, spread operator, filter()
function mergeArrays(...arrays) {
let combineArray = [];
let finalArray = [];
for (array of arrays) {
combineArray = [...combineArray, ...array];
}
finalArray = combineArray.filter(
(element, index) => combineArray.indexOf(element) === index
);
return finalArray;
}
- for...of...loop, spread operator, includes(), reduce(), Array.from()
function mergeArrays() {
let givenArray = Array.from(arguments);
let combineArray = [];
let finalArray = [];
for (array of givenArray) {
combineArray = [...combineArray, ...array];
}
finalArray = combineArray.reduce((acc, cha) => {
if (acc.includes(cha)) {
return acc;
} else {
return [...acc, cha];
}
}, []);
return finalArray;
}
Conclusion
There are many ways to solve problems programmatically. I will love to know other ways you solved yours in the comment section.
If you have questions, comments or suggestions, please drop them in the comment section.
You can also follow and message me on social media platforms.
Thank You For Your Time.
💖 💪 🙅 🚩
NJOKU SAMSON EBERE
Posted on March 19, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.