JSFiddle - React, Tailwind, and code Playground
by mariomc
HTML
<form id="formulario">
<input type="text" id="valores" placeholder="Coloque aqui os valores separados por vĂrgulas" style="width: 200px;"/>
<button id="submit">Enviar</button>
</form>
<h2 id="resultado"></h2>
JavaScript
function equi(A) {
//Check validity of A.
if(!Array.isArray(A)) return -1;
//initialize array to contain the results
var results = [];
//initialize var to contain the sum of array elements
var totalsum = 0;
//initialize var to contain sum of previous elements
var previoussum = 0;
//Loop first time to get the sum
for(var i = 0; i < A.length; i++){
totalsum += A[i];
}
//Loop second time to check for results
for(var i = 0; i < A.length; i++){
//If previoussum == totalsum - A[i] - previoussum , then an Equi Index is found
if(previoussum == totalsum - A[i] - previoussum){
results.push(i);
//comment out the line below to return the first equi index and about the rest of the loop
// return results;
}
//Add current element to current sum
previoussum += A[i];
}
//Check if there's any result
results = (results.length) ? results : -1;
//return the results
return results;
}
(function($){
$("#submit").click(function(e){
e.preventDefault();
$("#resultado").text(function(){
$("#valores").val();
});
});
})(jQuery);