patternjavascriptMinor
Checking two arrays for matches
Viewed 0 times
matchesarrayscheckingtwofor
Problem
Is there a better way to do this?
var duplicate = false;
for (var i = 0; i < acceptedFiles.length; i++) {
for (var j = 0; j < attachments.attachments.length; j++) {
if (attachments.attachments[j].name === acceptedFiles[i].name) {
duplicate = true;
}
}
}Solution
Presumably, once a
With JavaScript, the best thing would be to wrap up your
As this is a problem that applies to multiple languages, look at the
duplicate is found you don't need to continue looping:if (attachments.attachments[j].name === acceptedFiles[i].name) {
duplicate = true;
}With JavaScript, the best thing would be to wrap up your
for loops in a function:function containsDuplicate(acceptedFiles, attachments) {
for (var i = 0; i < acceptedFiles.length; i++) {
for (var j = 0; j < attachments.attachments.length; j++) {
if (attachments.attachments[j].name === acceptedFiles[i].name) {
return true;
}
}
}
return false;
}As this is a problem that applies to multiple languages, look at the
break keyword.Code Snippets
if (attachments.attachments[j].name === acceptedFiles[i].name) {
duplicate = true;
}function containsDuplicate(acceptedFiles, attachments) {
for (var i = 0; i < acceptedFiles.length; i++) {
for (var j = 0; j < attachments.attachments.length; j++) {
if (attachments.attachments[j].name === acceptedFiles[i].name) {
return true;
}
}
}
return false;
}Context
StackExchange Code Review Q#69617, answer score: 8
Revisions (0)
No revisions yet.