Generic code for Arrays - javascript

I want to create one loop that will access and push data from three arrays in JavaScript:
var tempArray1=new Array();
var tempArray2=new Array();
var tempArray3=new Array();
I tried following code:
for(var j=1; j<4; j++) {
var res = new Array();
var str = 'tempArray' + j;
res = str.split(" ");
}
but with this nothing happened.
Please help me to create generic code.

Brief
var res=[...tempArray1,...tempArray2,...tempArray3]
or more dynamic
var res=eval('[...tempArray1,...tempArray2,...tempArray3]') // since it is generic
DEMO :
var tempArray1=["I","love","JS"],tempArray2=["But","I'm"],tempArray3=["a crazy","JS","Programmer"]
function range(size){ /* for you case ,it returns : [1,2,3] */
return Array.from({length:size},(v,k)=>k+1)
}
function generate(size){
return eval('[...'+range(size).map((i)=>'tempArray'+i).join(',...')+']')
}
console.log(
generate(3)
)

var tempArray1 =[1,2,3];
var tempArray2 =[4,5];
var tempArray3 =[6];
function myConcat(){//This is the generic method
var result =[];
for (var i = 0; i < arguments.length; i++) {
result = result.concat(arguments[i]);
}
return result;
};
var conctenatedArray = myConcat(tempArray1,tempArray2,tempArray3);
console.log(conctenatedArray);
https://jsfiddle.net/8jwyzn0x/
**
OR
**
It would be good, if you wrap those array in a container object.
function myConcat(container){//This is the generic method
var result =[];
for(var i in container){
result = result.concat(container[i]);
}
return result;
};
var arrayContainer ={};
arrayContainer.tempArray1 =[1,2,3];
arrayContainer.tempArray2 =[4,5];
arrayContainer.tempArray3 =[6];
var conctenatedArray = myConcat(arrayContainer);
console.log(conctenatedArray);
https://jsfiddle.net/8jwyzn0x/1/

Related

Return multiple lines instead of console.log

I have the following code that produces the output I need using console.log
function product() {
var advertiserId = 1234;
var ord = 543210;
var productId = "id1|id2|id3|id4".split("|");
var productName = "product1|product2|product3|product4".split("|");
var productItemPrice = "10|20|30|40".split("|");
for(i = 0; i < productId.length; i++) {
console.log(advertiserId+"|"+ord+"|"+productId[i]+"|"+productName[i]+"|"+productItemPrice[i]);
}
}
product()
console.log result -
1234|543210|id1|product1|10
1234|543210|id2|product2|20
1234|543210|id3|product3|30
1234|543210|id4|product4|40
When changing console.log to return, only the first line is returned. return result -
1234|543210|id1|product1|10
Is there a way to return the same results as console.log?
You would usually push the lines to an array and return the array
function product() {
var advertiserId = 1234;
var ord = 543210;
var productId = "id1|id2|id3|id4".split("|");
var productName = "product1|product2|product3|product4".split("|");
var productItemPrice = "10|20|30|40".split("|");
var ret = [];
for(i = 0; i < productId.length; i++) {
ret.push(advertiserId+"|"+ord+"|"+productId[i]+"|"+productName[i]+"|"+productItemPrice[i]);
}
return ret;
}
let data = product();
console.log(data); // array holding the lines
// or join it with a newline
console.log(data.join("\n")); // lines as string
Push the results into an array then use the Array#join function.
function product() {
const advertiserId = 1234;
const ord = 543210;
const productId = "id1|id2|id3|id4".split("|");
const productName = "product1|product2|product3|product4".split("|");
const productItemPrice = "10|20|30|40".split("|");
const results = [];
for (let i = 0; i < productId.length; i++) {
results.push(`${advertiserId}|${ord}|${productId[i]}|${productName[i]}|${productItemPrice[i]}`);
}
return results;
}
const data = product();
console.log(data.join('\n'));
You could also use other console commands:
console.dir(data);
When you return from a function, it won't continue to execute. In your case, you can store each result and return them all at once.
function product() {
var advertiserId = 1234;
var ord = 543210;
var productId = "id1|id2|id3|id4".split("|");
var productName = "product1|product2|product3|product4".split("|");
var productItemPrice = "10|20|30|40".split("|");
var results = [];
for(i = 0; i < productId.length; i++) {
results.push(advertiserId + "|" + ord + "|" + productId[i] + "|" + productName[i]+ "|" +productItemPrice[i]);
}
return results;
}
results is now an array of strings that you can do what you want with.
Write the output to a variable then return. using return inside the loop will exit the loop
function product() {
var advertiserId = 1234;
var ord = 543210;
var productId = "id1|id2|id3|id4".split("|");
var productName = "product1|product2|product3|product4".split("|");
var productItemPrice = "10|20|30|40".split("|");
var output = "";
for(i = 0; i < productId.length; i++) {
output += advertiserId+"|"+ord+"|"+productId[i]+"|"+productName[i]+"|"+productItemPrice[i] + "\n";
}
return output;
}
product()
I think what you need is to store every result of the iteration on a variable, and then after the for loop you return it. Like
var a;
for loop... {
a += (all of your stuff) + '\n'
}
return a;
This should keep the break lines into the variable and so keep the indentation you want like console.log but into a variable.
If you need to have separated values you could store every line into a array and return the array after the for loop.
A return statement stops the function immediately and can only return a single value. You can add up data in the loop and then return at the end.
function product() {
var advertiserId = 1234;
var ord = 543210;
var productId = "id1|id2|id3|id4".split("|");
var productName = "product1|product2|product3|product4".split("|");
var productItemPrice = "10|20|30|40".split("|");
var result = [];
for(i = 0; i < productId.length; i++) {
result.push(advertiserId+"|"+ord+"|"+productId[i]+"|"+productName[i]+"|"+productItemPrice[i]);
}
return result;
}
product()
Can map() the values into an array and return the array or array joined to string
function product() {
var advertiserId = 1234;
var ord = 543210;
var productId = "id1|id2|id3|id4".split("|");
var productName = "product1|product2|product3|product4".split("|");
var productItemPrice = "10|20|30|40".split("|");
return productId.map(function(id, idx) {
return [
advertiserId,
ord,
productId[idx],
productName[idx],
productItemPrice[idx]
].join('|')
}).join('\n')
}
console.log(product());

Javascript loop through an array of objects and return the first value

I have created a function that is supposed to loop through an array of objects and return the first value of each object.
function getSheetSectionData(name){
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(name);
var sheetData = sheet.getDataRange().getValues();
var data = [];
for (var i = 0; i < sheetData.length; i++){
var obj = {};
obj = sheetData[i][0];
return sheetData[i][0];
}
data.push(obj);
}
It's only returning the first item in the first row/column. Any clues on what I'm missing?
You could use Object.keys together with Array#map to get just the first key value from each object.
data = sheetData.map(v => v[Object.keys(v)[0]]);
Working example:
var arr = [{foo: 'bar', bar: 'foo'},{foo: 'war', bar: 'foo'},{foo: 'mar', bar: 'foo'}],
res = arr.map(v => v[Object.keys(v)[0]]);
console.log(res);
How about this solution. Hope it helps!
var sheetData = [{name : "Mike", id: 10},{name : "Laura", id: 23},{name : "carl", id: 25},{name : "Lori", id: 23}];
var arr = []
for(var i in sheetData){
var someObject = sheetData[i];
arr.push(someObject[Object.keys(someObject)[0]]);
}
console.log(arr);
You have to move the return statement outside the loop.
function getSheetSectionData(name){
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(name),
sheetData = sheet.getDataRange().getValues(),
data = [];
for (var i = 0; i < sheetData.length; i++){
var obj = {};
obj = sheetData[i][0];
data.push(obj);
}
return data;
}
I'm not sure what your intent is, but probably it should be something like this?
function getSheetSectionData(name){
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(name);
var sheetData = sheet.getDataRange().getValues();
var data = [];
for (var i = 0; i < sheetData.length; i++){
var obj = {};
obj = sheetData[i][0];
data.push(obj);
}
return data;
}
UPDATE
As #grogx noted below, creation of a temporary object appears unnecessary in this context and the sample above could be optimized to
function getSheetSectionData(name){
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(name);
var sheetData = sheet.getDataRange().getValues();
var data = [];
for (var i = 0; i < sheetData.length; i++){
data.push(sheetData[i][0]);
}
return data;
}
Which can further be shortened to
function getSheetSectionData(name){
return SpreadsheetApp.getActiveSpreadsheet()
.getSheetByName(name)
.getDataRange()
.getValues()
.map((e) => e[0]);
}
However, we do not really know, what the original intent of the OP was. It may be the case, that that temporary object was indeed required for some sort of intermediate transformation, which was striped out from the MCVE.

How to count the JSON object and on the basis of count take the same output

How to count the JSON object and on the basis of count take the same output
var obj =
[
{"id":"0","name":"Mike Johnson","group":1},
{"id":"1","name":"Bob Smith","group":2},
{"id":"2","name":"Richard Thomas","group":3},
{"id":"3","name":"Betty White","group":16},
{"id":"4","name":"Tim Thompson","group":3},
{"id":"5","name":"Carl Lewis","group":16},
{"id":"6","name":"Kathy Towers","group":3},
{"id":"7","name":"Billy Bob","group":1},
{"id":"8","name":"Sally Bailey","group":1}
];
First I would like the count after it on the basis of count. I want same output like input.
for Count:-
var count = 0;
function getCount() {
for (var i = 0; i < obj.length; i++) {
count++;
}
return count;
}
for output :-
function showDetails() this is not giving the proper output
{
for(var j=0; j< count; j++){
obj.push([{j}]);
}
alert(obj.name);
}
alert(showDetails());
And I want an output like:-
var obj =
[
{"id":"0","name":"Mike Johnson","group":1},
{"id":"1","name":"Bob Smith","group":2},
{"id":"2","name":"Richard Thomas","group":3},
{"id":"3","name":"Betty White","group":16},
{"id":"4","name":"Tim Thompson","group":3},
{"id":"5","name":"Carl Lewis","group":16},
{"id":"6","name":"Kathy Towers","group":3},
{"id":"7","name":"Billy Bob","group":1},
{"id":"8","name":"Sally Bailey","group":1}
];
Can anybody help me please?
var data ="January,February,March,April,May,June,July,August,September,October";
var obj = data.split(',').map((item)=>{
return {
name:item
}
});
obj will be the desired output
var str = "January,February,March,April,May,June,July,August,September,October";
var arr = str.split(',').map(function(v) {
return {name: v};
});
console.log(arr);
var str = "January,February,March,April,May,June,July,August,September,October";
var months = str.split(",");
var result = [];
for (i in months)
{
var month = {};
month.name = months[i];
//you can do more things else here, for example:
//month.monthOfYear = (i+1);
//month.numberOfDay = 123123123;
result.push(month);
}
You can do something like this:
var array = string.split(",");
var finalArray = [];
array.forEach(function(item){
var obj = {
name: item
}
finalArray.push(obj);
});
console.log(finalArray);
MDN reference
use var array = string.split(',');
For a more ES2015 heavy version. Constants, arrow function and implicit return statement.
const str = 'January,February,March,April,May,June,July,August,September,October'
const result = str.split(',').map(name => ({name}))
console.log(result)

array object manipulation to create new object

var actual = [
{"country":"UK","month":"JAN","SR":"John P","AC":"24","PR":"2","TR":1240},
{"country":"AUSTRIA","month":"JAN","SR":"Brad P","AC":"64","PR":"12","TR":1700},
{"country":"ITALY","month":"JAN","SR":"Gim P","AC":"21","PR":"5","TR":900},
{"country":"UK","month":"FEB","SR":"John P","AC":"14","PR":"4","TR":540},
{"country":"AUSTRIA","month":"FEB","SR":"Brad P","AC":"24","PR":"12","TR":1700},
{"country":"ITALY","month":"FEB","SR":"Gim P","AC":"22","PR":"3","TR":600},
{"country":"UK","month":"MAR","SR":"John P","AC":"56","PR":"2","TR":1440},
{"country":"AUSTRIA","month":"MAR","SR":"Brad P","AC":"24","PR":"12","TR":700},
{"country":"ITALY","month":"MAR","SR":"Gim P","AC":"51","PR":"5","TR":200}
];
var expect = [
{month:"JAN",val: {"UK":"24","AUSTRIA":"64","ITALY":"21"}},
{month:"FEB",val: {"UK":"14","AUSTRIA":"24","ITALY":"22"}},
{month:"MAR",val: {"UK":"56","AUSTRIA":"24","ITALY":"51"}}
];
I have array of objects which i need to reshape for one other work. need some manipulation which will convert by one function. I have created plunker https://jsbin.com/himawakaju/edit?html,js,console,output
Main factors are Month, Country and its "AC" value.
Loop through, make an object and than loop through to make your array
var actual = [
{"country":"UK","month":"JAN","SR":"John P","AC":"24","PR":"2","TR":1240},
{"country":"AUSTRIA","month":"JAN","SR":"Brad P","AC":"64","PR":"12","TR":1700},
{"country":"ITALY","month":"JAN","SR":"Gim P","AC":"21","PR":"5","TR":900},
{"country":"UK","month":"FEB","SR":"John P","AC":"14","PR":"4","TR":540},
{"country":"AUSTRIA","month":"FEB","SR":"Brad P","AC":"24","PR":"12","TR":1700},
{"country":"ITALY","month":"FEB","SR":"Gim P","AC":"22","PR":"3","TR":600},
{"country":"UK","month":"MAR","SR":"John P","AC":"56","PR":"2","TR":1440},
{"country":"AUSTRIA","month":"MAR","SR":"Brad P","AC":"24","PR":"12","TR":700},
{"country":"ITALY","month":"MAR","SR":"Gim P","AC":"51","PR":"5","TR":200}
];
var outTemp = {};
actual.forEach(function(obj){ //loop through array
//see if we saw the month already, if not create it
if(!outTemp[obj.month]) outTemp[obj.month] = { month : obj.month, val: {} };
outTemp[obj.month].val[obj.country] = obj.AC; //add the country with value
});
var expected = []; //convert the object to the array format that was expected
for (var p in outTemp) {
expected.push(outTemp[p]);
}
console.log(expected);
Iterate through array and create new list
var actual = [
{"country":"UK","month":"JAN","SR":"John P","AC":"24","PR":"2","TR":1240},
{"country":"AUSTRIA","month":"JAN","SR":"Brad P","AC":"64","PR":"12","TR":1700},
{"country":"ITALY","month":"JAN","SR":"Gim P","AC":"21","PR":"5","TR":900},
{"country":"UK","month":"FEB","SR":"John P","AC":"14","PR":"4","TR":540},
{"country":"AUSTRIA","month":"FEB","SR":"Brad P","AC":"24","PR":"12","TR":1700},
{"country":"ITALY","month":"FEB","SR":"Gim P","AC":"22","PR":"3","TR":600},
{"country":"UK","month":"MAR","SR":"John P","AC":"56","PR":"2","TR":1440},
{"country":"AUSTRIA","month":"MAR","SR":"Brad P","AC":"24","PR":"12","TR":700},
{"country":"ITALY","month":"MAR","SR":"Gim P","AC":"51","PR":"5","TR":200}
];
var newList =[], val;
for(var i=0; i < actual.length; i+=3){
val = {};
val[actual[i].country] = actual[i]["AC"];
val[actual[i+1].country] = actual[i+1]["AC"];
val[actual[i+2].country] = actual[i+2]["AC"];
newList.push({month: actual[i].month, val:val})
}
document.body.innerHTML = JSON.stringify(newList);
This is the correct code... as above solution will help you if there are 3 rows and these will be in same sequnece.
Here is perfect solution :
var actual = [
{"country":"UK","month":"JAN","SR":"John P","AC":"24","PR":"2","TR":1240},
{"country":"AUSTRIA","month":"JAN","SR":"Brad P","AC":"64","PR":"12","TR":1700},
{"country":"ITALY","month":"JAN","SR":"Gim P","AC":"21","PR":"5","TR":900},
{"country":"UK","month":"FEB","SR":"John P","AC":"14","PR":"4","TR":540},
{"country":"AUSTRIA","month":"FEB","SR":"Brad P","AC":"24","PR":"12","TR":1700},
{"country":"ITALY","month":"FEB","SR":"Gim P","AC":"22","PR":"3","TR":600},
{"country":"UK","month":"MAR","SR":"John P","AC":"56","PR":"2","TR":1440},
{"country":"AUSTRIA","month":"MAR","SR":"Brad P","AC":"24","PR":"12","TR":700},
{"country":"ITALY","month":"MAR","SR":"Gim P","AC":"51","PR":"5","TR":200}
];
var tmpArray = [];
var obj =[];
for(var k=0; k<actual.length; k++){
var position = tmpArray.indexOf(actual[k].month);
if(position == -1){
tmpArray.push(actual[k].month);
val = {};
for(var i=0; i<actual.length; i++){
if(actual[i].month == actual[k].month){
val[actual[i].country] = actual[i]["AC"];
}
}
obj.push({month: actual[k].month, val:val});
}
}

Loop through two Array in JavaScript and Constructing a function

I have Two Arrays in Javascript as shown below :
Array one = new Array();
one.push(20061001);
one.push(20061002);
one.push(20061003);
one.push(20061120);
Array two = new Array();
two.push(3.0);
two.push(3.1);
two.push(3.2);
two.push(3.3);
Now Some how i need to loop through this Array and construct a function as shown
function NoisyData() {
return "" +
"Date,A\n" +
"20061001,3.0\n" +
"20061002,3.1\n" +
"20061003,3.2\n" +
"20061120,4.0\n" ;
}
Please help me as how to do this ??
How about this?
var one = new Array();
one.push(20061001);
one.push(20061002);
one.push(20061003);
one.push(20061120);
var two = new Array();
two.push('3.0');
two.push('3.1');
two.push('3.2');
two.push('3.3');
function NoisyData() {
var result = "Date,A\n";
for(var i = 0; i < one.length;i++){
result += one[i] + "," + two[i] + "\n";
}
return result;
}
alert(NoisyData());
The faster way for long array is :
var one = new Array();
one.push(20061001);
one.push(20061002);
one.push(20061003);
one.push(20061120);
var two = new Array();
two.push(3.0);
two.push(3.1);
two.push(3.2);
two.push(3.3);
function NoisyData() {
var ret = [];
ret.push("Date,A");
for (var i=0;i<one.length;i++){
ret.push(one[i]+','+two[i]);
}
return ret.join('\n');
}
alert(NoisyData());
Your code can be a lot shorter. You can't type variables (like Array one) in javascript. To declare an Array most of the time an Array literal is sufficient.
If your arrays have the same length, you can use the code hereby to combine them into the string you need:
var one = [20061001,20061002,20061003,20061120]
, two = [3.0,3.1,3.2,3.3]
, combine = function(a1,a2){
var i = -1, len = a1.length, res = ['Date,A'];
while(++i < len){
res.push(a1[i]+','+a2[i].toPrecision(2));
}
return res.join('\n');
}(one,two);
Try it # http://jsfiddle.net/KooiInc/jdn6U/
You mean
function NoisyData() {
var txt = "Date,A\n"
for (var i=0, n=one.length;i<n;i++) {
txt += one[i]+","+two[i]+"\n"
}
return txt
}
UPDATE based on KooiInc's posts:
<script>
var one = [20061001,20061002,20061003,20061120]
, two = [3.0,3.1,3.2,3.3]
, combined = function(res,two){
var i = one.length;
while(i--){
res[i]+=','+two[i].toPrecision(2);
}
res.splice(0,0,'Date,A');
return res.join('\n')
}(one.slice(0),two);
alert(combined);
</script>
Instead of one.slice(0) one.clone() can be implemented as
Array.prototype.clone = function() { return this.slice(0); }
or just pass one itself instead if it is OK to modify the original array

Categories

Resources