create object array based on max value in javascript - javascript

I would like to know how to create object array based on max value in javascript,
based on max value how to create object as shown
for(var i = 0; i<=max;i++){
var result = [];
result.push({id: `${i}`, name: `s${i}`});
return result;
}
var max = 20;
var obj = [{id: 0, name: ""}]
Expected Output
result = [
{id: 1, name: "s1"},
{id: 2, name: "s2"},
{id: 3, name: "s3"},
..
..
{id: 20, name: "s20"}
]

Firstly, if you want to return a value you'll need a function. Then you'll have to take the initialization of the array out of the for loop, otherwise you'll be initializing it with every iteration. Then you can push the new objects to the array and finally you can return the newly populated array, like so:
const createObjectArray = (max) => {
var result = [];
for (var i = 0; i <= max; i++) {
result.push({ id: `${i}`, name: `s${i}` });
}
return result;
}
var max = 20;
let result = createObjectArray(max);
console.log(result);

Related

How to group elements of array

I have an array:
var arr = ['User1','123456','User2','456789','User3','546544'];
How can I get array of object like this:
var arr2 = [{name: 'User1', id: 123456},{name: 'User2', id: 456789}, {name: 'User3', id: 546544}];
I tried this:
arr.forEach(function (item, i, arr) {
arr2.push(
{
name: arr[i],
id: arr[i + 2]
}
);
});
In a simple way, you need to do two things:
Check if the length is even.
Push it as how you require, by incrementing the loop twice.
var arr = ['User1', '123456', 'User2', '456789', 'User3', '546544'];
var arrObj = [];
if (arr.length % 2 === 0)
for (var i = 0; i < arr.length; i += 2)
arrObj.push({
"name": arr[i],
"id": parseInt(arr[i + 1], 10),
});
console.log(arrObj);
Look at the comments inside the code.
const arr = ['User1', '123456', 'User2', '456789', 'User3', '546544'];
// Ok, so what you to do is to group the infos and create a new object
// There is many function you can use, in the following example, I will use
// Array.reduce
// We gonna call couple, two values that goes together, like :
// User1 and 123456
// User2 and 456789
// ...
const ret = arr.reduce((tmp, x, xi) => {
// Add nothing for the first value of the couple
// We gonna ignore, User1, User2 and User3
if (xi % 2 === 0) return tmp;
return [
...tmp,
// Add a new value in the array
{
// The name is the first value of the couple
name: arr[xi - 1],
// The id is the second value of the couple
id: x,
},
];
}, []);
console.log(ret);
The for loop works on all versions of all computers and has the added advantage of being able to skip the index directly, something forEach can only do with a lot of extra code. Also forEach is slower than the for loop.
var arr1 = ['User1', '123456', 'User2', '456789', 'User3', '546544'], arr2 = [];
for (var i = 0; i < arr1.length - 1; i += 2) { // here is the i+=2
arr2.push({
"name": arr1[i],
"user": arr1[i + 1] // here is the i+1
});
}
console.log(arr2)
Or terser array
var arr1 = ['User1', '123456', 'User2', '456789', 'User3', '546544'], arr2 = [];
for (var i = 0; i < arr1.length - 1; i += 2) {
arr2.push({
[arr1[i]]: arr1[i + 1]
});
}
console.log(arr2)
A solution to your problem would be as follow :
var arr2 = [];
for (var i = 0; i < arr.length; i = i + 2) {
arr2.push({name : arr[i], id: arr[i + 1]})
}
Next time time try to show your trial code, you'll progress much more this way.

How to convert Object of Arrays to Objects

I have some data coming from the MVC controller in the below format:
{id: Array[3], city: Array[3]}
I wanted to convert that data into
[Object, Object, Object]
which will have the structure Object0{id, city}, Object1{id, city}, Object2{id, city}
I tried the below method but didnt work out
angular.forEach(data, function(){
vm.Cities = {
id :data.citiesIDs,
city : data.citiesStr
}
});
Can anyone please give me a hint as in where i am going wrong or what is the best way to achieve this. Thanks in advance.
You don't really need Angular for this, plain Javascript works just as well.
function transform(object) {
var result = [];
for (var i = 0; i < object.id.length; i++) {
result.push({
id: object.id[i],
city: object.city[i]
});
}
return result;
}
Then you can call your helper with your data:
var list = transform(data); // <-- list of (id,city) objects
Keep in mind the function assumes both of your id and city arrays are of the same length (which really wouldn't make sense if they weren't), BUT for the case they're not of the same length, you would want to make a minor change in your for loop:
var maxLen = Math.max(object.id.length, object.city.length);
for (var i = 0; i < maxLen; i++)
This is a simple JS operation and here is the demo
// Assuming obj is defined and both obj.id and obj.city are arrays
var obj = {
id: [25, 82, 188, 141],
city: ['Tokyo', 'Munich', 'Los Angeles', 'Sao Paolo'],
};
var max = Math.max(obj.id.length, obj.city.length);
var results = [];
for(var i = 0; i < max; i++) {
var converted = {
id: obj.id[i] ? obj.id[i] : null,
city: obj.city[i] ? obj.city[i] : null
};
results.push(converted);
}
console.log('Coverted array', results);
Very simple example. Iterate over one of the arrays and grab from the other by index.
var cities = []
angular.forEach(data.id, function(id, index) {
var city = {id: id, city: data.city[index]};
cities.push(city);
});
Iterator can help you. e.g.:
var data = {id: [1,2], city: ['Curitiba','São Paulo']};
var array = [];
for(var prop in data){
var length = data[prop].length;
for(var z = 0; z < length; z++){
if(!array.hasOwnProperty(z)){
array[z] = {};
}
array[z][prop] = data[prop][z];
}
}
console.log(array);// [Object{city:'Curitiba',id:1},Object{city:'São Paulo',id:2}]

How to combine and group arrays in javascript

So I'm getting values and I want to put them into an array:
var values = {25,23,21}
var unit = {PCS,KG,PCS}
I want it to be like this when I put them in an array
array = {25:PCS,23:KG,21:PCS}
and group and add them depending on the unit so the final result will be something like this
totalval = {46:PCS,23:KG}
I can only put those values into separate arrays but I don't know how can I combine and group them..
https://jsfiddle.net/wyh5a2h2/
I went through reorganizing your code so it makes a bit of sense and came up with this: Hopefully it suits what you are attempting to do:
var items = [
{value: 25, unit: 'PCS'},
{value: 23, unit: 'KG'},
{value: 21, unit: 'PCS'},
]
var numPCS = 0, numKG = 0;
var result = [];
items.forEach(function(elem, index) {
if(elem.unit==='PCS') {
numPCS+=elem.value;
}
if(elem.unit==='KG') {
numKG+=elem.value;
}
});
result.push({value: numPCS, unit: 'PCS'});
result.push({value: numKG, unit: 'KG'});
console.log(result);
Here is the result:
var values = [25, 23, 21],
unit = ['PCS', 'KG', 'PCS'],
result = {},
tmpval = {},
totalval = {};
for (var i = 0; i < values.length; i++) {
result[values[i]] = unit[i];
tmpval[unit[i]] || (tmpval[unit[i]] = 0);
tmpval[unit[i]] += values[i];
}
for (var i in tmpval) {
totalval[tmpval[i]] = i;
}
// result: { '21': 'PCS', '23': 'KG', '25': 'PCS' }
// totalval: { '23': 'KG', '46': 'PCS' }
you will have to create objects first and then put them into an array
var obj1 = {
value: 25,
unit: "PCS"
};
...
var array = [ obj1, obj2, obj3, ... ];
then aggregate them accordingly

Convert nested array to object

I am looking for a solution, to push/convert array items into a object back, without using keys?
function pleaseBuy(){
var args = arguments;
for(var i = 0; i < arguments[0].length; ++i) {
args += args[i];
};
};
function getList(){
return ["pepsi","cola","7up"];
}
var list = ({ favorite: "drpepper"}, getList())
pleaseBuy(list)
Expected result:
args = ({ favorite: "drpepper"}, "pepsi", "cola", "7up")
No need for the pleaseBuy function, I'd say:
function getList(){
return ["pepsi","cola","7up"];
}
var list = getList().concat( { favorite: "drpepper" } );
// ^ NB should be :
// or favorite first
var list = [{ favorite: "drpepper" }].concat(getList());
/*
list now contains:
['pepsi, 'cola','7up',{ favorite: "drpepper" }]
*/
An object allways contains key-value pairs. If you want to convert an array to an object, you'll thus have to assign keys and values. For example:
var arr = [1,2,3,4,'some'], arr2Obj = {};
for (var i=0;i<arr.length;i=i+1){
arr2Obj[arr[i]] = i;
}
/*
arr2Obj now contains:
{
1: 0,
2: 1,
3: 2,
4: 3,
some: 4
}
*/
Other example:
var arr = [1,2,3,4,'some'], arr2Numbers = {};
for (var i=0;i<arr.length;i=i+1){
arr2Numbers[arr[i]] = !isNaN(Number(arr[i]));
}
/*
arr2Numbers now contains:
{
1: true,
2: true,
3: true,
4: true,
some: false
}
*/
Do you mean the javascript push function?
Use .unshift() docs to prepend to an array.
var list = getList();
list.unshift( { favorite="drpepper"});
// [{ favorite="drpepper"}, "pepsi", "cola", "7up"]
Demo at http://jsfiddle.net/Ds9y5/
Try this:
var array = ["pepsi","cola","7up"];
array.push({ favorite: "drpepper"});
Or
var array2 = ["pepsi","cola","7up"];
var array = [{favorite: "drpepper"}];
for(var ctr = 0 ; ctr < array2.length ; ctr++){
array.push(array2[ctr]);
}
var s = getList();
s.unshift({ favorite : "drpepper"}); // at the first place in array
s.push({ favorite : "drpepper"}); // at the last place in array
alert(s);
JavaScript push() Method
JavaScript unshift() Method

An array converting question

I have an array below,
var array = {
"Id":[1,2,3],
"Name":["one","two","five"],
"row":[8,9,7]
}
but I want to transform it into
var array2 =
{"data":
[
{"Id":1,"Name":"one","Row:8"},
{"Id":2,"Name":"two","Row:9"},
{"Id":3,"Name":"five","Row:7"},
]
}
Is this possible?
This should do it:
// make sure the new object is initialized
var array2 = { data: [] };
// Count the number of items in array.Id and start iterating
for (var i=0,t=array.Id.length; i < t; i++) {
// Note that array.Id = [1,2,3] does not result in corresponding keys
// array.Id[0] corresponds to value 1!
array2.data.push({
Id: array.Id[i],
Name: array.Name[i],
Row: array.Row[i]
});
}
var array2 = {data: []};
for (i in array.Id) {
array2.data.push({
Id: array.Id[i],
Name: array.Name[i],
row: array.row[i]
});
}
Didn't test it
it's not an array. it's an object.
var myArr = [1,2,3]; //Array definition
var myObj = {test:"1",test2:"2"}; //Object Definition
var array = [1,[1,2,3]]; // multidimensional array

Categories