Is it possible to make this function using indexOf() ?

If so, please tell me how I could accomplish this.

 var array = ["a","b","c","d"]; function func_insert_array(){ var get_array = document.getElementById("insert_array").value; console.log(get_array); var separation = get_array.split(","); console.log(separation); for (var i = 0; i < separation.length; i++) { var deleteIndex; var array_2 = array.filter(function(value, index) { if (value == separation[i]) { deleteIndex = index; return true; } else { return false; } }); if (array_2.length > 0) { var windows = confirm("такое значение уже есть " + array[deleteIndex]); if (windows == true) { array.splice(deleteIndex,1); } } console.log(array); if (array_2.length == 0 ) { array.push(separation[i]); } console.log(array_2); } document.getElementById("arr").innerHTML = array; } 
  • And you just need .indexOf() , there are more convenient methods, like includes() - Alexander Zaytsev
  • IndexOf is desirable, but I would love to look at the option with includes. - Android Games
  • variable array on the 10th page (???) from where - Alexander Zaytsev
  • Oh, she is higher, did not insert it. I'll fix it now. - Android Games
  • Add an example of the second array. and the expected result. - Grundy

1 answer 1

Made the function this way, the issue is resolved.

 var array = [1,2,3,4,5]; function func_insert_array() { var get_array = document.getElementById("insert_array").value; var separation = get_array.split(","); console.log(separation); for (var i = 0; i < separation.length; i++) { var deleteIndex = array.indexOf(separation[i]); if (deleteIndex >= 0) { var windows = confirm("Такой элемент уже существует, удалить его? " + array[deleteIndex]); if (windows == true) { array.splice(deleteIndex,1); } } if (deleteIndex == -1) { array.push(separation[i]); } console.log(separation[i]); console.log(deleteIndex); } console.log(array); document.getElementById("arr").innerHTML = array; }