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

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]);
}

Related

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!!
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);

find number of string matches from array to array in javascript?

I need to find number of strings in array b that contains in array arr. I got the output but i need it in this order.[[3,6,0],[1,3,1]]
here my code goes.
var arr = [["00","00","00","01","01","01","01","01","01"],["000","100","01","01","01"]];
var b = ["00","01",10];
var cc = [];
for (var i=0;i<b.length;i++) {
var k = [];
for (var y=0;y<arr.length;y++) {
var a = 0;
for (var x=0;x<arr[y].length;x++) {
if ((arr[y][x].substring(0,2)).indexOf(b[i]) != -1) {
a++;
}
}
k.push(a)
}
cc.push(k);
}
console.log(JSON.stringify(cc));// output :[[3,1],[6,3],[0,1]]
Actual output : [[3,1],[6,3],[0,1]]
Expected output : [[3,6,0],[1,3,1]]
I want the result either in javascript or jquery.
As you have in b number 10 you need convert it to String and then search in array, because arr contains only strings
var arr = [
["00","00","00","01","01","01","01","01","01"],
["000","100","01","01","01"]
];
var b = ["00", "01", 10];
var len, i, j, key, result = [], counts = [], count = 0;
for (i = 0, len = arr.length; i < len; i++) {
for (j = 0; j < b.length; j++) {
count = 0;
key = String(b[j]);
count = arr[i].filter(function (el) {
return el.slice(0, 2) === key;
}).length;
counts.push(count);
}
result.push(counts);
counts = [];
}
console.log(JSON.stringify(result));
Version for IE < 9, where there is not .filter method
var arr = [
["00","00","00","01","01","01","01","01","01"],
["000","100","01","01","01"]
];
var b = ["00", "01", 10];
var len,
key,
result = [],
counts = [],
i, j, k, count;
for (i = 0, len = arr.length; i < len; i++) {
for (j = 0; j < b.length; j++) {
count = 0;
key = String(b[j]);
for (k = 0; k < arr[i].length; k++) {
if (arr[i][k].slice(0, 2) === key) {
count++;
}
}
counts.push(count);
}
result.push(counts);
counts = [];
}
console.log(JSON.stringify(result));
Seems like there are some typo in your sample input. Following code may help.
var arr = [["00","00","00","01","01","01","01","01","01"],["00","10","01","01","01"]];
var b = ["00","01","10"];
var cc = [];
arr.forEach(function(ar,i){
cc[i] = [];
b.forEach(function(a,j){
cc[i][j] = ar.filter(function(d){ return d==a }).length;
});
});
alert(JSON.stringify(cc));
Or
var arr = [
["00", "00", "00", "01", "01", "01", "01", "01", "01"],
["00", "10", "01", "01", "01"]
];
var b = ["00", "01", "10"];
var cc = arr.map(function(ar) {
return b.map(function(a) {
return ar.filter(function(d) {
return d == a
}).length;
})
});
alert(JSON.stringify(cc));

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 to list all combinations in this scenario? [duplicate]

I'm trying to write an algorithm to get all the possible combinations of N elements inside a multi dimensional array of M elements.
Something like:
function getCombinations(arr, n){
...
}
var arr = [ ["A"],["B","C"],["D","E"]];
var n = 2;
getCombinations(arr,n);
This should produce:
[
["A","B"],["A","C"],["A","D"],["A","E"],
["B","D"],["B","E"],
["C","D"],["C","E"]
]
The number of elements inside the array may vary, the only thing set is the number of elements of the combinations.
The order doesn't matter but you cannot repeat, I mean ["A","B"] == ["B","A"], so the second one is not take in consideration.
Any help?
ChrisB solution had a mistake, he wasn't caching the length of the loop before the arr.shift, and it was not returning the last combination, I think this will do the job:
function getCombinations (arr, n) {
var i, j, k, elem, l = arr.length, childperm, ret = [];
if (n == 1){
for (i = 0; i < arr.length; i++) {
for (j = 0; j < arr[i].length; j++) {
ret.push([arr[i][j]]);
}
}
return ret;
}
else {
for (i = 0; i < l; i++) {
elem = arr.shift();
for (j = 0; j < elem.length; j++) {
childperm = getCombinations(arr.slice(), n-1);
for (k = 0; k < childperm.length; k++) {
ret.push([elem[j]].concat(childperm[k]));
}
}
}
return ret;
}
}
getCombinations([["A"],["B"],["C","D"]], 2);
// [["A", "B"], ["A", "C"], ["A", "D"], ["B", "C"], ["B", "D"]]
getCombinations([["A"],["B"],["C"],["D"]], 2);
// [["A", "B"], ["A", "C"], ["A", "D"], ["B", "C"], ["B", "D"], ["C", "D"]]
Updated
Per your restriction that elements that are contained in the same array in the beginning cannot be combined I've modified the algorithm to the following:
Here is the updated jsfiddle that now even outputs the data in the correct format :) http://jsfiddle.net/QKg2H/7/
function getCombinations(arr, n)
{
if(n == 1)
{
var ret = [];
for(var i = 0; i < arr.length; i++)
{
for(var j = 0; j < arr[i].length; j++)
{
ret.push([arr[i][j]]);
}
}
return ret;
}
else
{
var ret = [];
for(var i = 0; i < arr.length; i++)
{
var elem = arr.shift();
for(var j = 0; j < elem.length; j++)
{
var childperm = getCombinations(arr.slice(), n-1);
for(var k = 0; k < childperm.length; k++)
{
ret.push([elem[j]].concat(childperm[k]));
}
}
}
return ret;
}
}
The algorithm is still recursive, but now it will consider each of the second degree elements in turn, but not with each other. Other than that, it still pops off one element and then appends the permutations of all of the remaining elements. I hope it's straightforward.

How to merging javascript arrays and order by position?

Is there anyway to merge arrays in javascript by ordering by index/position. I'm try to accomplish this and haven't been able to find any examples of this.
var array1 = [1,2,3,4]
var array2 = [a,b,c,d]
var array3 = [!,#,#,$]
var merged array = [1,a,!,2,b,#,3,c,#,4,d,$]
I know you can use concat() to put one after the other.
As long as the arrays are all the same length you could just do:
var mergedArray = [];
for (var i = 0, il = array1.length; i < il; i++) {
mergedArray.push(array1[i]);
mergedArray.push(array2[i]);
mergedArray.push(array3[i]);
}
EDIT:
For arrays of varying lengths you could do:
var mergedArray = [];
for (var i = 0, il = Math.max(array1.length, array2.length, array3.length);
i < il; i++) {
if (array1[i]) { mergedArray.push(array1[i]); }
if (array2[i]) { mergedArray.push(array2[i]); }
if (array3[i]) { mergedArray.push(array3[i]); }
}
This should work for arrays of ANY length:
var mergeArrays = function () {
var arr = [],
args = arr.slice.call(arguments),
length = 0;
for (var i = 0, len = args.length; i < len; i++) {
length = args[i].length > length ? args[i].length : length;
}
for (i = 0; i < length; i++) {
for (var j = 0; j < len; j++) {
var value = args[j][i];
if (value) {
arr.push(value);
}
}
}
return arr;
};
Example:
var array1 = [1,2,3,4];
var array2 = ['a','b','c','d','e','f','g','h','i','j','k','l'];
var array3 = ['!','#','#','$','%','^','&','*','('];
mergeArrays(array1, array2, array3);
// outputs: [1, "a", "!", 2, "b", "#", 3, "c", "#", 4, "d", "$", "e", "%", "f", "^", "g", "&", "h", "*", "i", "(", "j", "k", "l"]
This would work also (a little more terse syntax):
var mergeArrays = function () {
var arr = [],
args = arr.slice.call(arguments),
length = Math.max.apply(null, args.map(function (a) { return a.length; }));
for (i = 0; i < length; i++) {
for (var j = 0, len = args.length; j < len; j++) {
var value = args[j][i];
if (value) {
arr.push(value);
}
}
}
return arr;
};
For arrays that are all the same size, where you pass one or more arrays as parameters to merge:
function merge()
{
var result = [];
for (var i=0; i<arguments[0].length; i++)
{
for (var j=0; j<arguments.length; j++)
{
result.push(arguments[j][i]);
}
}
return result;
}
var array1 = ['1','2','3','4'];
var array2 = ['a','b','c','d'];
var array3 = ['!','#','#','$'];
var merged = merge(array1, array2, array3);
Nothing built in, but it wouldn't be hard to manage:
var maxLength = Math.max(array1.length, array2.length, array3.length),
output = [];
for (var i = 0; i < maxLength; i++) {
if (array1[i] != undefined) output.push(array1[i]);
if (array2[i] != undefined) output.push(array2[i]);
if (array3[i] != undefined) output.push(array3[i]);
}
try this...
var masterList = new Array();
var array1 = [1,2,3,4];
var array2 = [a,b,c,d];
var array3 = [!,#,#,$];
for(i = 0; i < array1.length; i++) {
masterList.push(array1[i]);
masterList.push(array2[i]);
masterList.push(array3[i]);
}
It looks like you want to "zip" some number of same-length arrays into a single array:
var zip = function() {
var numArrays=arguments.length
, len=arguments[0].length
, arr=[], i, j;
for (i=0; i<len; i++) {
for (j=0; j<numArrays; j++) {
arr.push(arguments[j][i]);
}
}
return arr;
};
zip([1,2], ['a', 'b']); // => [1, 'a', 2, 'b']
zip([1,2,3], ['a','b','c'], ['!','#','#']); // => [1,'a','#',...,3,'c','#']
If the input arrays could be of different length then you've got to figure out how to deal with that case...
Yes, there is some way to do that. Just:
loop through the larger array,
until at the currently processed position both arrays have elements, assign them one-by-one to the new array,
after the shorter array ends, assign only elements from the longer array,
The resulting array will have the elements ordered by the index from the original arrays. From your decision depends, position in which one of these arrays will have higher priority.
This works for any number of array and with arrays of any length.
function myMerge() {
var result = [],
maxLength = 0;
for (var i = 0; i < arguments.length; i++) {
if (arguments[i].length > maxLength) { maxLength = arguments[i].length; }
}
for (var i = 0; i < maxLength; i++) {
for (var j = 0; j < arguments.length; j++) {
if (arguments[j].length > i) {
result.push(arguments[j][i]);
}
}
}
return result;
}
Eli beat me to the punch up there.
var posConcat = function() {
var arrays = Array.prototype.slice.call(arguments, 0),
newArray = [];
while(arrays.some(notEmpty)) {
for(var i = 0; i < arrays.length; i++) {
if(arguments[i].length > 0)
newArray.push(arguments[i].shift());
}
}
return newArray;
},
notEmpty = function() { return arguments[0].length > 0; };
Usage:
var orderedArray = posConcat(array1,array2,array3);
Sample: http://jsfiddle.net/HH9SR/

Categories