How to make it so that when comparing two arrays, when the first identical element is found, the search ends and this element is recorded in the 3rd array. In the example, the array is obtained with: ((AB)) + C, but it is necessary that the following result be output: the array with: (AB) + C array a :() in the array and the remaining elements!

var a = "ABC()-()+"; var b = "(AB)+C"; var c = []; document.write("массив а: "); document.write(a); document.write("<br>"); document.write("массив b: "); document.write(b); for (var i = 0; i < b.length; i++) { for (var j = 0; j < a.length; j++) { if (b[i] == a[j]) { c.push(b[i]); } } } document.write("<br>"); document.write("массив c: "); document.write(c); document.write("<br>"); document.write("массив a: "); document.write(a); 

    1 answer 1

    Apparently you need a break statement.

    to change the array a you can use the replace method

     var a = "ABC()-()+"; var b = "(AB)+C"; var c = []; document.write("массив а: "); document.write(a); document.write("<br>"); document.write("массив b: "); document.write(b); for (var i = 0; i < b.length; i++) { for (var j = 0; j < a.length; j++) { if (b[i] == a[j]) { c.push(b[i]); break; } } a = a.replace(b[i],''); } document.write("<br>"); document.write("массив c: "); document.write(c.join('')); document.write("<br>"); document.write("массив a: "); document.write(a); 

    • But how to make it so that in the array and the remaining elements are displayed, in this case: array a: () - Svetlana
    • it is necessary to change the array as well, in this code it does not change - Grundy
    • @ Svetlana, updated the answer - Grundy
    • I understood everything, thanks) - Svetlana
    • "to change the array a" :( And where is the array a? - Qwertiy ♦