Insert values in specific position of array javascript - 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!!

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;
}
EDIT: To get the number of spaces in the array
var arr = ["A", "A", " " , " ", " " , "B" ,"C " , " "];
var spaceCount = 0;
arr.forEach(function(i) { if(i == " ") spaceCount++; });
console.log(spaceCount)
EDIT 2: To count consecutive spaces in an array
var arr = ["A", "A", " " , " ", " " , "B"," ", " " ,"C " , " "];
var count = 1;
var countArr = [];
for (var i = 0; i < arr.length; i++) {
if(arr[i] == " "){
if(arr[i+1] == arr[i]){
count ++;
}else {
countArr.push(count);
count = 1;
}
}
};
console.log(countArr)
EDIT 3: To get consecutive space count + starting position
var arr = [" ", "A", "A", " " , " ", " " , "B"," ", " " ,"C " , " "];
var count = 1;
var countArr = [];
var pos = 0;
for (var i = 0; i < arr.length; i++) {
if(arr[i] == " "){
if(arr[i] === arr[i+1]){
count ++;
}else {
countArr.push({'pos': pos, 'count': count});
count = 1;
}
}else{
pos = i+1;
}
};
console.log(countArr)

var array = ["A", "", "", "", "B", "B", "B"];
var cantidad = 2;
for (var x = 0; x < array.length; x++) {
if (array[x] === "") {
if (cantidad >0){
array.splice(x, 1, "C");
cantidad--;
}
}
}
function codeAddress() {
alert(array);
}
window.onload = codeAddress;
Here's a solution, I realized you can solve this problem in a lot of different ways, mine is not necessarily the best approach.
Good luck.

EDIT: This is a working solution for both questions.
var array = ["","","","","","",""];
function addValues(num, value) {
for(var i=0; i<num; i++) {
for(var j=0; j<array.length; j++){
if(array[j] ==="") {
array[j] = value;
break;
}
}
}
}
function removeValues(value) {
for(var i=0; i<array.length; i++) {
if(array.indexOf(value) !== -1) {
array[i] = "";
}
}
}
addValues(3, 'A');
addValues(2, 'B');
addValues(1, 'C');
removeValues('A');
addValues(2, 'D');
addValues(2, 'E');
console.log(array);

Related

For a given array of string, each with an item name, group all the string by item name

str_arr= ["a", "a", "b", "c", "b"]
The resulting array should be ["a 2", "b 2", "c 1"].
I can't get the desired result with the following code.
function foo(str) {
var a = [], b = [], prev;
for ( var i = 0; i < str.length; i++ ) {
if ( str[i] !== prev ) {
a.push(str[i]);
b.push(1);
} else {
b[b.length-1]++;
}
prev = arr[i];
}
return [a, b];
}
var result = foo(str_arr);
var newA = result[0].map((e, i) => e + " " + result[1][i]+ "<br>");
You could take an object for counting the items and
get the keys of the object,
sort by count descending and by key ascending,
map key and count as string.
Then return the array.
function foo(transactions) {
var counts = {};
for (var i = 0; i < transactions.length; i++) {
counts[transactions[i]] = (counts[transactions[i]] || 0) + 1;
}
return Object
.keys(counts)
.sort((a, b) => counts[b] - counts[a] || a > b || -(a < b))
.map(k => k + ' ' + counts[k]);
}
var transactions = ["notebook", "notebook", "mouse", "keyboard", "mouse"],
result = foo(transactions);
console.log(result);
No sort required. Original array unaffected.
function group(arr) {
var hits = {}, group_arr = [];
for (var i = 0; i < arr.length; i++) hits[arr[i]] = (hits[arr[i]] || 0) + 1;
for (var hit in hits) Object.prototype.hasOwnProperty.call(hits, hit) && group_arr.push(hit + " " + hits[hit]);
return group_arr;
}
console.log(group(["a", "a", "b", "c", "b"]));
Here's a function to add counts to the unique words in the array.
This one does it more old-school, by iterating over the sorted array.
function countDistinctWords (arr) {
if (arr.length === 0) return arr;
arr = arr.sort();
let result = [];
let n = 1;
for (let i = 1; i < arr.length; i++) {
if (arr[i-1] == arr[i]) {n++}
if (arr[i-1] !== arr[i]) {
result.push(arr[i-1]+' '+n);
n=1;
}
}
result.push(arr[arr.length-1]+' '+n);
return result;
}
str_arr= ["a", "a", "b", "c", "b"];
var str_arr2 = countDistinctWords(str_arr);
console.log(str_arr2);

Remove duplicates of single "a" value from array if array has multiple "a" elements

I am looking for a simple solution. I have an array like array("a","b","c","a","g");
Now when i try splice or custom remove function , it removes all "a" elements from array.
What i want is when i remove "a" from the array , then the array should finally have 1 "a" element only inside it and remove all other dulicates of "a".
Now consider another case , when my array is like array("a","a","b","c","a") , then after removing "a" , the array should like array("a","b","c").
Help needed,
Thanks in advance
Try this snippet
var arr = ["a","a","b","c","a"];
var arrayLength = arr.length;
for (var i = 0; i < arrayLength; i++) {
for (var j = i + 1; j < arrayLength;) {
if (arr[j] == arr[i]) {
for (var k = j; k < arrayLength; k++) {
arr[k] = arr[k + 1];
}
arrayLength--;
} else
j++;
}
}
var newArr = [];
for (var i = 0; i < arrayLength; i++) {
newArr.push(arr[i]);
}
console.log(newArr);
You can make use of the filter method like:
var duplicates = ["a","a","b","c","a"];
var withoutDuplicates = duplicates.filter(function(currentValue, index) {
return duplicates.indexOf(currentValue) == index;
});
console.log(withoutDuplicates); // Array [ "a", "b", "c" ]
As also stated here:
Remove Duplicates from JavaScript Array
Documentation: http://www.w3schools.com/jsref/jsref_filter.asp
You could use Set and keep only unique items in the array.
var unique = array => array.filter((set => a => !set.has(a) && set.add(a))(new Set));
console.log(unique(["a", "b", "c", "a", "g"]));
console.log(unique(["a", "a", "b", "c", "a"]));
Different style
var unique = function (array) {
return array.filter(function (a) {
if (!this.has(a)) {
this.add(a);
return true;
}
}, new Set);
};
console.log(unique(["a", "b", "c", "a", "g"]));
console.log(unique(["a", "a", "b", "c", "a"]));
ES5 with Object as hash
var unique = function (array) {
return array.filter(function (a) {
if (!this[a]) {
return this[a] = true;
}
}, Object.create(null));
};
console.log(unique(["a", "b", "c", "a", "g"]));
console.log(unique(["a", "a", "b", "c", "a"]));
Can try this one
var array = ["a","a","b","c","a"];
var filterIfMultiple = function (data) {
var count = 0;
array = array.filter(function(val) {
if (val === data) count+=1;
if(val !== data || (val === data && count <= 1)){
return val;
}
});
};
filterIfMultiple("a");
console.log(array);
Another process without passing any parameter using ES6 Set object
var array = ["a","a","b","c","a","b"];
function filterIfDuplicate() {
array = Array.from(new Set(array));
}
filterIfDuplicate();
console.log(array);

Merging of array in javascript or jquery

var first = [ "a", "b", "c" ];
var second = [ "d", "e", "f" ];
My output should be
var final=["a~d","b~e","c~f"];
where '~' is delimiter.
Check if the length of both arrays.
See comments inline in the code:
var first = [ "a", "b", "c" ];
var second = [ "d", "e", "f" ];
var len = first.length > second.length ? first.length : second.length;
// Get the length of the array having max elements
var separator = '~';
var final = [];
for(var i = 0; i < len; i++) {
// If no element is present, use empty string
first[i] = first[i] ? first[i] : '';
second[i] = second[i] ? second[i] : '';
final.push(first[i] + separator + second[i]);
// Add the new element in the new array
}
Here is a function for this... you can specify the behavior, if the arrays are not the same length:
function merge(arr1,arr2,delimiter){
var i,len;
var delim = delimiter.toString();
var res = [];
if(arr1.length !== arr2.length){
//TODO: if arrays have different length
}else{
len = arr1.length;
for(i=0; i< len; i++){
res[i] = arr1[i] + delim + arr2[i];
}
}
return res;
}
merge(['a','b','c'],['d','e','f'],'~');
This is exactly what Haskell's zipWith function does. It takes a function (which takes two arguments and does something with them to return only one value) and two arrays, looping through the arrays and passing it's values into the function.
Here is a non-recursive example:
var zipWith = function(zippingFunction, arr1, arr2){
var length = arr1.length < arr2.length ? arr1.length : arr2.length;
var retArray = [];
for (i = 0; i< length; i++){
retArray.push(zippingFunction(arr1[i], arr2[i]));
}
return retArray;
};
console.log(zipWith(function(a, b){return a + b}, [1,2,3], [4,5,6]));
console.log(zipWith(function(a, b){return a + "~" + b}, ["1","2","3"], ["4","5","6"]));
Which returns:
[ 5, 7, 9 ]
[ '1~4', '2~5', '3~6' ]
var first = [ "a", "b", "c" ];
var second = [ "d", "e", "f" ];
var final=[];
// assuming they are the same length
for(var i = 0; i < first.length; i++) {
final.push(first[i] + '~' + second[i]);
}
console.log(final);
var first = [ "a", "b", "c" ];
var second = [ "d", "e", "f" ];
var count = -1;
var arr=new Array();
first.forEach(function(entry) {
count++;
arr[count] = entry + "~" + second[count];
});
alert(arr);
Use Like This You Get Your Desired Result
Demo is Here http://jsfiddle.net/7evx02zf/6/
var final1=[];
var first = [ "a", "b", "c" ];
var second = [ "d", "e", "f" ];
$.each(first, function( index, value ) {
var tmp=value+"~"+second[index];
final1[index]=tmp;
});
console.log(final1);
JQUERY only solution.Try this,should work.
Try this...
<script>
var first = ["a", "b", "c"];
var second = ["d", "e", "f"];
var third=new Array();
for(i=0;i<first.length;i++)
{
var data=first[i]+'~'+second[i];
third.push(data);
}
console.log(third);
</script>
Output:["a~d", "b~e", "c~f"]
A JavaScript only solution.
Try this. This solution assumes that both arrays are equal in length.
//your initial array
var first = [ "a", "b", "c" ];
var second = [ "d", "e", "f" ];
//set up final array
var final = [];
//loop through
for (var ii = 0, nn = first.length; ii < nn; ii++)
{
//add to final array each item of first and secon
final.push(first[ii]+"~"+second[ii]);
}
//print to console
console.log(final);
Output:
["a~d", "b~e", "c~f"]
If you're not sure if length are the same, this will go up to the shortest
//your initial array
var first = [ "a", "b", "c", "g" ];
var second = [ "d", "e", "f" ];
//set up final array
var final = [];
//loop through until the length of shortest
for (var ii = 0, nn = (first.length < second.length ? first.length : second.length); ii < nn; ii++)
{
//add to final array each item of first and secon
final.push(first[ii]+"~"+second[ii]);
}
//print to console
console.log(final);
Output:
["a~d", "b~e", "c~f"]
Try this code:
var final=[];
var first = [ "a", "b", "c" ];
var second = [ "d", "e", "f" ];
for(var i = 0; i < first.length; i++) {
final.push(first[i] + '~' + second[i]);
}
console.log(final.toString());
Example:
Click Here for Demo
You could try this JS only solution. It's only 1 line and works regardless of both first and second lengths:
var first = [ "a", "b", "c", "x", "y" ];
var second = [ "d", "e", "f" ];
var final = [];
first.forEach(function(v,i) {final[i] = first[i] + '~' + (second[i] || '')});

How might I return multiple arrays with equal values from a larger array with mixed values?

I have an array that after being sorted appears like this:
var arr = ["a", "a", "b", "b", "b", "b", "c", "c", "c"];
There are 2 "a" Strings, 4 "b" Strings, and 3 "c" Strings.
I am trying to return 3 separate arrays, returning them one at a time from a loop, containing only matching values. So, upon the first iteration, the returned array would appear as newArr = ["a", "a"], the second as newArr = ["b", "b", "b", "b"] and on the third iteration as newArr = ["c", "c", "c"].
However, this is a small array of predefined values, and I need an algorithm that can perform the same operation on an array of unknown size, unknown elements, and with an unknown number of like elements. (and keep in mind that the array is already sorted to begin with, in this context)
Here's my crazy code that is displaying some unusual, and incorrect, results:
var arr = ["a", "a", "b", "b", "b", "b", "c", "c", "c"];
for(var index = 0; index < arr.length; index++)
{
var test = "";
var newArr = []; // resets the new array upon each iteration
var str = arr[index]; // initialized as the next unique index-value
for(var i = index; i < arr.length; i++)
{
if(arr[i] == str)
{
newArr.push(arr[k]);
test += arr[i] + " ";
}
else
{
index = i; // changing the outer loop variable
break; // exiting the inner loop
}
} // end of inner loop
window.alert(test);
setValues(newArr);
} // end of outer loop
function setValues(arrSorted)
{
var here = document.getElementById("here");
for(var i = 0; i < arrSorted.length; i++)
{
here.innerHTML += arrSorted[i] + " ";
}
here.innerHTML += "<br />";
} // end of setValues function
var arr = ["a", "a", "b", "b", "b", "b", "c", "c", "c"];
var arrays = {};
for (var i=0;i<arr.length;i++) {
if (!arrays[arr[i]]) arrays[arr[i]] = [];
arrays[arr[i]].push(arr[i]);
}
this will give you the equivalent of
arrays = {};
arrays['a'] = ['a','a'];
arrays['b'] = ['b','b','b','b','b'];
arrays['c'] = ['c','c','c'];
You can use a function like this to divide the array into several arrays:
function divide(arr) {
var subArrays = [];
var current = null;
var subArray = null;
for (var i = 0; i < arr.length; i++) {
if (arr[i] != current) {
if (subArray != null) subArrays.push(subArray);
current = arr[i];
subArray = [];
}
subArray.push(arr[i]);
}
if (subArray != null) subArrays.push(subArray);
return subArrays;
}
Demo: http://jsfiddle.net/Guffa/d8CBD/
This is how I would do it:
var arr = ["a", "a", "b", "b", "b", "b", "c", "c", "c"];
var out = [], prev;
for (var i = 0, j = 0, len = arr.length; i < len; i++) {
if (arr[i] !== prev || !out.length) {
out[j++] = [prev = arr[i]];
} else {
out[j - 1].push(prev);
}
}
//out -> [["a","a"],["b","b","b"],["c","c","c"]]
Demo
Note: the || !out.length check is just handle arrays that start with undefined correctly, but feel free to remove it if this will never be the case

Joining each item of an array with the items of another array

Consider this:
[ ["a", "b"], ["c", "d"], ["e"] ]
How can this be tranformed to:
[ "a c e", "a d e", "b c e", "b d e" ]
// edit: tested and works
function product(set) {
if(set.length < 2)
return set[0];
var head = set.shift(), p = product(set), r = [];
for(var j = 0; j < head.length; j++)
for(var i = 0; i < p.length; i++)
r.push([head[j]].concat(p[i]));
return r;
}
var set = [
[ "a", "b", "c"],
[ "D", "E" ],
[ "x" ]
];
var p = product(set);
for(var i = 0; i < p.length; i++)
document.write(p[i] + "<br>");
This works:
<html><body><script>
var to_join = [ ["a", "b"], ["c", "d"], ["e"] ];
var joined = to_join[0];
for (var i = 1; i < to_join.length; i++) {
var next = new Array ();
var ends = to_join[i];
for (var j = 0; j < ends.length; j++) {
for (var k = 0; k < joined.length; k++) {
next.push (joined[k]+ " " + (ends[j]));
}
}
joined = next;
}
alert (joined);
</script></body></html>
Try concat method:
var newArr=[];
for(var i=0; i< arr.length; i++)
{
newArr = newArr.concat(arr[i]);
}

Categories