Tuesday, May 21, 2024
 Popular · Latest · Hot · Upcoming
125
rated 0 times [  127] [ 2]  / answers: 1 / hits: 19789  / 13 Years ago, fri, november 18, 2011, 12:00:00

I am stuck in this. I got 2 arrays, I don't know the length of each one, they can be the same length or no, I don't know, but I need to create a new array with the numbers no common in just a (2, 10).



For this case:



    var a = [2,4,10];
var b = [1,4];

var newArray = [];

if(a.length >= b.length ){
for(var i =0; i < a.length; i++){
for(var j =0; j < b.length; j++){
if(a[i] !=b [j]){
newArray.push(b);
}
}
}
}else{}


I don't know why my code never reach the first condition and I don't know what to do when b has more length than a.


More From » arrays

 Answers
181

It seems that you have a logic error in your code, if I am understanding your requirements correctly.



This code will put all elements that are in a that are not in b, into newArray.



var a = [2, 4, 10];
var b = [1, 4];

var newArray = [];

for (var i = 0; i < a.length; i++) {
// we want to know if a[i] is found in b
var match = false; // we haven't found it yet
for (var j = 0; j < b.length; j++) {
if (a[i] == b[j]) {
// we have found a[i] in b, so we can stop searching
match = true;
break;
}
// if we never find a[i] in b, the for loop will simply end,
// and match will remain false
}
// add a[i] to newArray only if we didn't find a match.
if (!match) {
newArray.push(a[i]);
}
}





To clarify, if



a = [2, 4, 10];
b = [4, 3, 11, 12];


then newArray will be [2,10]


[#89048] Wednesday, November 16, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
denis

Total Points: 260
Total Questions: 87
Total Answers: 87

Location: Venezuela
Member since Thu, Jul 15, 2021
3 Years ago
;