How could i compine two array based on the index. - javascript

so what i have is three (or more) array with different sizes something like the following :
a ['x1' , 'x2', 'x3'];
b ['y1','y2']
c ['z1']
i want to create a string like the following :
x1,y1,z1 - x2,y2 - x3
any idea how the logic behind doing something like this?

Just because I like to be contrary (who'd a thunk it!), here's an alternative using plain for loops:
var data = [
['q1','q2'],
['x1', 'x2', 'x3'],
['y1', 'y2', 'y3', 'y4', 'y5'],
['z1']
];
var result = [];
for (var i=0, iLen=data.length; i<iLen; i++) {
temp = data[i];
for (var j=0, jLen=temp.length; j<jLen; j++) {
if (!result[j]) {
result.push([temp[j]]);
} else {
result[j].push(temp[j]);
}
}
}
alert(result.join(' - ')); // q1,x1,y1,z1 - q2,x2,y2 - x3,y3 - y4 - y5
If support for sparse arrays is required (i.e. with missing members or values of undefined or null or whatever), that's not too hard to implement.

var arrays = [a, b, c];
var groupings = [];
var idx = 0;
while (true) {
var items = [];
for (var i = 0; i < arrays.length; i++) {
if (arrays[i].length > idx) {
items.push(arrays[i][idx]);
}
}
if (!items.length)
break;
else
groupings.push(items.join(','));
idx++;
}
console.log(groupings.join(' - '));

Let's say you have an array of arrays of arbitrary number, then you can use code like this to iterate through them:
var data = [
['q1', 'q2'],
['x1', 'x2', 'x3'],
['y1', 'y2', 'y3', 'y4', 'y5'],
['z1']
];
var output = "";
var term, j = 0;
while (true) {
term = [];
for (var i = 0; i < data.length; i++) {
if (data[i].length > j) {
term.push(data[i][j]);
}
}
// if no more terms, then all arrays are exhausted
// so it's time to break out of the loop
if (term.length == 0) {
break;
}
if (output) {
output += " - ";
}
output += term.join(",");
j++;
}
alert(output);
And, a working example here: http://jsfiddle.net/jfriend00/fZKbp/

Related

How to clean , from a given string?

I have data like this.
var abc =",,,,,,,,,,,,,,,paul,2000,12sc21,logan,123,21sdf34,vfsarwe,456456,32fd23";
abc = abc.split(",");
let stub={};
var results=[];
var key=["name","value","acc"];
var i=0;
var j=0;
for( var i = 0 ; i <abc.length - 1;i++){
stub[key[j]=abc[i];
j++
if(j==3){
results.push(stub);
stub={};
j=0;
}
}
abc = results;
I would like to get those values arranges in form of array of object having those 3 keys:
output should be:
abc = [{"name": "paul", "value": "2000","acc":"12sc21"},{"name":"logan","value":"123","acc":"21sdf34"},{"name":"vfsarwe","value":"456456","acc":"32fd23"}];
but not able to get the desired output. this output only comes when string don't have ,,,,,, in starting. But the data i'm getting is sometimes having ,,,,, in stating.
You can use abc.replace(/(^[,\s]+)/g, '') to remove leading commas or whitespace from the String. Your for loop is also not running for long enough; it is looping until there is only one element left in the Array and then stopping.
Change
for(var i = 0 ; i < abc.length-1; i++)
To
for(var i = 0 ; i < abc.length; i++)
var abc =",,,,,,,,,,,,,,,paul,2000,12sc21,logan,123,21sdf34,vfsarwe,456456,32fd23";
abc = abc.replace(/(^[,\s]+)|([,\s]+$)/g, '').split(",");
let stub={};
var results=[];
var key=["name","value","acc"];
var i=0;
var j=0;
for(var i = 0 ; i < abc.length; i++){
stub[key[j]]=abc[i];
j++
if(j==3){
results.push(stub);
stub={};
j=0;
}
}
abc = results;
console.log(abc);
You can use .replace(/^\,+/, '') to remove all leading commas, then split by comma to get an array, then loop over this array using 3 as step and construct your results:
var abc = ",,,,,,,,,,,,,,,paul,2000,12sc21,logan,123,21sdf34,vfsarwe,456456,32fd23";
var arr = abc.replace(/^\,+/, '').split(",");
var results = [];
for (var i = 0; i < arr.length; i = i + 3) {
results.push({
"name": arr[i],
"value": arr[i + 1],
"acc": arr[i + 2]
});
}
Demo:
var abc = ",,,,,,,,,,,,,,,paul,2000,12sc21,logan,123,21sdf34,vfsarwe,456456,32fd23";
var arr = abc.replace(/^\,+/, '').split(",");
var results = [];
for (var i = 0; i < arr.length; i = i + 3) {
results.push({
"name": arr[i],
"value": arr[i + 1],
"acc": arr[i + 2]
});
}
console.log(results);
You are on the right track with splitting your data on ,. You can then split the data in to chunks of 3, and from there map each chunk to a dict.
var data = ",,,,,,,,,,,,,,,paul,2000,12sc21,logan,123,21sdf34,vfsarwe,456456,32fd23";
var split = data.split(",");
var chunked = [];
while (split.length) {
chunked.push(split.splice(0,3));
}
var res = chunked.map((i) => {
if (!i[0] || !i[1] || !i[2]) {
return null;
}
return {
name: i[0],
value: i[1],
acc: i[2]
};
}).filter((i) => i !== null);
console.log(res);
You can use:
abc.replace(/,+/g, ',').replace(/^,|,$/g, '').split(',');
The regEx replaces removes the data that you are not interested in before performing the split.
or
abc.split(',').filter(Boolean);
The filter(Boolean) will remove the items from the array that could be the equivalent of false once the array has been instantiated.
EDIT:
var abc =",,,,,,,,,,,,,,,paul,2,000,12sc21,logan,123,21sdf34,vfsarwe,456456,32fd23";
var array = abc.replace(/,+/g, ',').replace(/^,|,$/g, '').split(/,([0-9,]+),/);
array = array.filter(Boolean).reduce(function(acc, item) {
if (item.match(/^[0-9,]+$/)) {
acc.push(item);
} else {
acc = acc.concat(item.split(','));
}
return acc;
}, []);

How to get the product of numbers gotten from combinations of datasets

I have a combinatoric script that's working fine, actually got most of it from the IBM dev website. But I want to be able to not just show the possible combinations, but also extract the numbers on each combination and get the product of the entire numbers. The project am working on mixes numbers (quantity) with strings (codename). So after combining them, i extract the number from each string and get the product of all the numbers in each combination. As shown;
[A2,B4,C5] = 2*4*5 = 40
Here is my javascript code that gets the combination, not to worry, I ran it with a test array of numbers 1-6, without the characters as shown above.
var Util = function() {
};
Util.getCombinations = function(array, size, start, initialStuff, output) {
if (initialStuff.length >= size) {
output.push(initialStuff);
} else {
var i;
for (i = start; i < array.length; ++i) {
Util.getCombinations(array, size, i + 1, initialStuff.concat(array[i]), output);
}
}
}
Util.getAllPossibleCombinations = function(array, size, output) {
Util.getCombinations(array, size, 0, [], output);
}
// Create an array that holds numbers from 1 ... 6.
var array = [];
for (var i = 1; i <= 6; ++i) {
array[i - 1] = i;
}
var output = [];
var resultArray = [];
Util.getAllPossibleCombinations(array, 4, output);
for(var j=0; j<output.length; j++) {
resultArray += output[j] + "=" + "<br />";
}
document.getElementById("test").innerHTML = resultArray;
});
I tried running this code inside the last for loop to get my multiplication, but it's just not executing, i must be doing something wrong. Here is the code;
var inputval = output[j].replace(/[^,.0-9]/g, '');
inputval = inputval.slice(0, -1);
var hoArray = inputval.split(',');
var cunt= hoArray.length;
var ans=1;
for(var m=0; m<cunt; m++)
{
ans *= hoArray[m];
}
Thanks for your assistance in advance.
walk the array then walk the string, then cast and see if it is an integer then tally and sum the product.
let array = ['A20', 'B11', 'C5'];
function getProduct(ar) {
let product = 1;
for (let x of ar) {
let semiProduct = [];
for (let i of x) {
if (Number.isInteger(+i)) {
semiProduct.push(i);
}
}
product *= semiProduct.join('');
}
return product;
}
console.log(getProduct(array))
You could also use a regular expression.
let array = ['A20', 'B11', 'C5'];
function getProduct(ar) {
let product = 1;
for (let x of ar) {
product *= x.match(/\d+/)[0];
}
return product;
}
console.log(getProduct(array))
If you want a way to generate permutations, you can utilize a generator to make things more concise.
let array = ['A20', 'B11', 'C5'];
function* permu(arr, l = arr.length) {
if (l <= 0) yield arr.slice();
else
for (var i = 0; i < l; i++) {
yield* permu(arr, l - 1);
const j = l % 2 ? 0 : i;
[arr[l - 1], arr[j]] = [arr[j], arr[l - 1]];
}
}
console.log(
Array.from(permu(array))
);
When I run that code in the console it throws an error because output[j] is an array [1,2,3,4] and it looks like you're expecting it to be a string. Arrays do not have a replace method in JS.
You should run this:
var count= hoArray.length;
var ans=1;
for(var m=0; m<count; m++)
{
ans *= hoArray[m];
}
And put output[j] instead of hoArray. And don't do any of this:
var inputval = output[j].replace(/[^,.0-9]/g, '');
inputval = inputval.slice(0, -1);
var hoArray = inputval.split(',');

how to loop through array of arrays and combine values

I need to loop through a array of arrays and calculate the sum of each array. The Json is a kendo-ui chart series with arrays of x,y coordinates. I need to return the sum of the x,y values. linq.js or javascript will work. thanks
JSON
var =series = [{
"style":"smooth",
"color":"blue",
"data":[
[600,30000],
[800,60000],
[1100,100000]
],
"name":"Subject Property",
"removeByNames":[
["Product1"],
["Product2"],
["Product3"]
],
"$$hashKey":"object:30"
}]
So for this example i would need to end up with this
var newSeries = [{
"style":"smooth",
"color":"blue",
"data":[
[30600],
[60800],
[101100]
],
"name":"Subject Property",
"removeByNames":[
["Product1"],
["Product2"],
["Product3"]
],
"$$hashKey":"object:30"
}]
for(var i=0;i<series[0].data.length;i++){
var val = series[0].data[i];
newSeries.data[i] = val[0] + val[1];
}
You can use loop and use reduce
var series = [{
...
}]
for (var i = 0; i < series.length; i++) {
for (var j = 0; j < series[i].data.length; j++) {
series[i].data[j] = series[i].data[j].reduce(function(p,c) {
return p + c;
});
}
}
Demo: http://jsfiddle.net/kv854c61/1/
you just need to loop the values in your data properties something like this..
for( var i - 0; i < series.length-1; i++){
for( var j - 0; j < series[i].data.length-1; i++){
var result = series[i].data[j][0] + series[i].data[j][1];
series[i].data[j] = result;
}
}
now it would make sense to add the new data array, so as not to overwrite
series[i].new_data[j] = result;
Array.map is quite useful in this case:
// extracts the data entries of each item in the series
var data = series.map(function(item){ return item["data"]; });
function sum(point) {
return point[0] + point[1];
// in case point is of arbitrary dimension use Array.reduce:
// return point.reduce(function(prev, cur){ return prev + cur; }, 0);
}
var sums = data.map(function(arr){
return arr.map(function(point){
return sum(point);
});
});
// sums now contains an array of array of sums
// e.g. [[30600,60800,101100]]

Looping through an array to create an object in Javascript

I want to write a function that takes an array such as:
var columns = ['distance', 'times', 'acceleration']
Then from this array, I want to generate something like this:
[{id: id_0, distance: 0, times: 0, acceleration: 0}, {id: id_1, distance: 1, times: 1, acceleration: 1}]
Notice that we have 2 objects here, but I want it to be whatever number I pass in to my parameter. Here is what I have:
generateData: function(rows, columns) {
var generatedData = [];
for (var i = 0, rowLen = rows.length; i < rowLen; i++) {
for (var n = 0; i < columns.length; n++) {
// not sure how to construct an object here from looping through my columns array
generatedData.push({
id: 'id_ + n',
// confused here
});
}
return generatedData;
}
}
This is the perfect place to dynamically create your own function. Try this:
function createArrayOfObjects(columns, count) {
var objectProps = new Array(columns.length);
for (var i = 0; i < columns.length; i++){
//":j" will be the variable j inside the dynamic function
objectProps[i] = columns[i] + ":j";
}
var funcBody = "var arr = new Array(count);" +
"for(var j = 0; j < count; j++){" +
"arr[j] = {" + objectProps.join(',') + "};" +
"}" +
"return arr;";
//Create a new function and call it with count as the parameter, returning the results
return new Function("count", funcBody)(count);
}
var count = 10;
var columns = ['distance', 'times', 'acceleration'];
createArrayOfObjects(columns.concat('id'), count);
This has the benefit of only having to loop over the columns array once where other solutions require nested loops.
JSPerf
I am giving you away the initial non-optimized solution. Its upto you to do the optimizations.
generateData: function(rows, columns) {
var generatedData = [];
for (var i = 0; i < rows.length; i++) {
var myObj = {};
myObj["id_" + i] = i;
for (var n = 0; n < columns.length; n++) {
myObj[columns[n]] = i;
}
generatedData.push(myObj);
}
return generatedData;
}
A functional approach that will take the object properties from the passed in array, instead of hard-coding them, might look something like this inside the for loop to populate an array named 'rows' with property names coming from the values of an array named 'cols':
cols.forEach(function(cv, ci, ca) { rows[ri][cv] = ri; });
See the snippet for a full example. Note that, in this example, I'm just shoving the current index of "rows" into the object as the property value.
var columns = ['distance', 'times', 'acceleration'];
function generateData(numRows, cols) {
rows = new Array(numRows);
for(ri=0; ri < rows.length; ri++) {
rows[ri] = { id: ri };
cols.forEach(function(cv, ci, ca) {
rows[ri][cv] = ri;
});
}
return rows;
}
data = generateData(5, columns);
console.log(data);

group array division

this code http://jsfiddle.net/minagabriel/5MQ77/
var flowShadeBigArray =[] ;
var x = [7, 411, 780]
var y = [286, 712, 1058]
for( var i = 0 ; i< x.length;i++){
for(var index = x[i]; index <= y[i] ; index++ ){
var temp = [] ;
temp.push(index) ;
flowShadeBigArray.push(temp);
}
}
console.log(JSON.stringify(flowShadeBigArray));
generate the following array
[[7],[8],[9],[10],[11],[12],[13],[14]................[1056],[1057],[1058]]
i want to create a three arrays inside flowShadeBigArray and have the [x[i] ... y[i] ]
grouped together:
example
[ [ [7]....[286] ] , [ [411]...[712] ] ,[ [780]...[1058] ] ]
NOTE i still need to keep each of these numbers as an array so i can use it an an index for something else
THANKS
Just move the temp initialization to the first loop, before the second, and the .push() to the first loop after the second (or before, doesn't matter).
var flowShadeBigArray = [];
var x = [7, 411, 780]
var y = [286, 712, 1058]
for (var i = 0; i < x.length; i++) {
var temp = [];
for (var index = x[i]; index <= y[i]; index++) {
temp.push(index);
}
flowShadeBigArray.push(temp);
}
http://jsfiddle.net/5MQ77/1/
If each individual number belongs in its own Array, then change this:
flowShadeBigArray.push(temp);
to this:
flowShadeBigArray.push([temp]);
-edited
function range(from, to) {
var arr = [];
while (from <= to) {
arr.push([i++]);
}
return arr;
}
var result = [];
for (var i=0; i<x.length; i++) {
result.push(range(x[i], y[i]));
}

Categories