I have two arrays here, I would like to compare both array and extract out the values that does not match. The '3' stands for module credit and 'nfu3ai' stands for module code so both of them comes together, which basically means 'nfu3ai' has credit of '3' and 'sjfru1' has credit of '6'. So the problem with my code now is when I compare the two arrays I only get ['nfu3ai'] and not 3 since 'sgvnfs' has a credit of '3' as well so it gets remove.
['6', 'sjfru1', '3', 'nfu3ai', '3', 'sgvnfs']
['3', 'sgvnfs', '6', 'sjfru1']
This is my code:
const set1 = new Set(moduleAndCreditByUser);
const set2 = new Set(moduleToUpdate);
const newModule = [
...moduleAndCreditByUser.filter(item =>
!set2.has(item)),
...moduleToUpdate.filter(item =>
!set1.has(item))];
Results:
['nfu3ai']
I want to get:
['3', 'nfu3ai']
CodePudding user response:
to get the result ['3', 'nfu3ai'], you need to modify the code to take into account the relationship between module credits and module codes. Here's one way to do it
const moduleAndCreditByUser = ['6', 'sjfru1', '3', 'nfu3ai', '3', 'sgvnfs'];
const moduleToUpdate = ['3', 'ST1501', '6', 'ST0007'];
const newModule = [];
for (let i = 0; i < moduleAndCreditByUser.length; i = 2) {
const credit = moduleAndCreditByUser[i];
const code = moduleAndCreditByUser[i 1];
if (!moduleToUpdate.includes(credit) || !moduleToUpdate.includes(code)) {
newModule.push(credit, code);
}
}
console.log(newModule);
I hope that it could help.
CodePudding user response:
I can't get it, you have an array with six and four values in it. Where is the declared that " '3' stands for module credit and 'nfu3ai' stands for module code"
The array shows only six values ['6', 'sjfru1', '3', 'nfu3ai', '3', 'sgvnfs']
, but none of them are together. Maybe you should write it in a multiple Array like
[['6', 'sjfru1'], [ '3', 'nfu3ai'], ['3', 'sgvnfs']]
Is that what you want?
To compare your array you could create a function
function compareArrays(array1, array2) {
if (array1.length !== array2.length) {
return 'Arrays are of different lengths';
}
for (let i = 0; i < array1.length; i ) {
if (array1[i] !== array2[i]) {
return `Values are different at index ${i}. (${array1[i]} vs ${array2[i]})`;
}
}
return 'Arrays have the same values';
}
const array1 = [1, 2, 3, 4];
const array2 = [1, 2, 3, 4];
console.log(compareArrays(array1, array2)); // "Arrays have the same values"
const array3 = [1, 2, 3, 4];
const array4 = [4, 3, 2, 1];
console.log(compareArrays(array3, array4)); // "Values are different at index 0 (1 vs 4)"