Eliott Eliott - 1 month ago 19
PHP Question

Insert values in specific position of array javascript

First I am creating an array with an specific size.

$("#bntSize").one('click', function(e){
var memoria = $("#memoria").val();
console.log(memoria)

html = "";

for(var i = 0; i < memoria ; i++){
html += "<div class='square' name='mem"+i+"' data-id='"+i+"' data-pos='"+i+"' >"+i+"</div>";
arrayMemoria.push('');
}
console.log(arrayMemoria)
$("#contenedor").html(html);

});


If memoria is equal to 7 I am getting this:

["", "", "", "", "", "", ""]


Now I am giving some values to the array:

var nada = 0;

function firstFit(){

var cantidad = $("#ffinput").val();
var value = $("#ffinput2").val();
/*console.log(cantidad)*/

if(nada == 0){
for (nada ; nada < cantidad ; nada++) {
arrayMemoria.splice(nada , 1 , value);
nada = nada;
}
}
else{

for (nada; nada < arrayMemoria.length ; nada++) {
arrayMemoria.splice(nada , 1 , value);
nada = nada;
}
}


Here cantidad: how many spaces I am suppose to use in array & value: just a value.

So if I put => cantidad = 3 and value = A

["A", "A", "A", "", "", "", ""]


Then if I want to put => cantidad = 2 and value = B

["A", "A", "A", "B", "B", "B", "B"]


But I am trying to get this:

["A", "A", "A", "B", "B", "", ""]


and if I put => cantidad = 1 and value = C

["A", "A", "A", "B", "B", "C", ""]


And my second problem

If I do remove the values equals to A and I am inserting => cantidad = 2 AND VALUE = D
I am suppose to get this:

["D", "D", "", "B", "B", "C", ""]


How to count the available space in my array? cause if I want to insert

cantidad = 1 and value = E , I need to get the first available space

["D", "D", "E", "B", "B", "C", ""]


If someone can help me please!!

Answer

You can try the following code

	var arr = ["", "", "", "", "", "", ""];
    arr = insertValue(3, "A", arr);
    console.log(arr);
    arr = insertValue(2, "B", arr);
    console.log(arr);
    arr = insertValue(1, "C", arr);
    console.log(arr)
    arr = removeValue("A", arr);
    console.log(arr)
    arr = insertValue(2, "D", arr);
    console.log(arr)
    
    
	function insertValue(cantidad, value, arr){
		var arrLength = arr.length;
		var count = 0;
		for (var i = 0; i < arrLength; i++) {
			if(arr[i] == "" && count < cantidad){
				arr[i] = value;
				count ++;
			}
		};
      return arr;
	}

	function removeValue(value, arr){
		var arrLength = arr.length;
		for (var i = 0; i < arrLength; i++) {
			if(arr[i] == value){
				arr[i] = "";
			}
		};
      return arr;
	}