I am trying to achieve the following result. I have a textarea, I want to transform all the text (by line) that will be input inside this textarea in an array. Once the text has been input, I want to check if there are duplicates in the entries.
To do so, I: 1) create an array (named myarrayfromtextarea, below) from the textarea 2) I create an array (named checkArray below) of the duplicates value 3) I loop through all the values in my first array and I check for matches in the second array.
Theoretically, it works well but I tried to input the following values in the textarea:
- dwdw
- dwdwdwdwdwdwdwdw
- dwdwdwdw
- dwdwdwdw
- dwdwdwdwdwdwdwdwdwdw
I expected to find only one duplicate value (row 3 and 4) but incredibly, when I run --> checkArray.indexOf(array[i]) also the row 1 shows a match.
Can you help me?
var myarrayfromtextarea = $('#My_textarea').val().split('\n'); // create array from textarea
console.log("array from textarea: " + myarrayfromtextarea)
var myArr = myarrayfromtextarea; /// here I start to find duplicates
var obj = {};
var checkArray = "["
myArr.forEach(function(item) {
if (typeof obj[item] == 'number') {
checkArray = checkArray + item + ",";
obj[item]++;
} else {
obj[item] = 1;
}
});
checkarraylenght = (checkArray.length - 1)
checkArray = checkArray.substring(0, checkarraylenght)
checkArray = checkArray + "]" + '';
console.log("checkarray = " + checkArray)
myarrayfromtextarea = myarrayfromtextarea + '';
var array = myarrayfromtextarea.split(',');
var arrayLength = array.length;
for (var i = 0; i < arrayLength; i++) {
if (checkArray.indexOf(array[i]) == -1) {
console.log("Not a duplicate: " + array[i]);
} else {
console.log("Duplicate value: " + array[i]);
}
//Do something
}