Convert and calculate an array javascript - javascript

I have an array like the one you can see in the pic. I have seen array with objects in it, array with numbers and/or strings. But I don't know how to deal with this kind of array. It looks like each line is an object in the array but there is no "{}". (Sorry, I am new to javascript)
My question is..I want a new array like below, how can I convert it?
newArray = [
{
time:Q2.14,
percent:...
},
{
time:Q3.14,
percent:...
},
{
time:Q4.14,
percent:...
},
....
]
The percent is the value for the current time devided by sum of all numbers.
Appreciate!

That's not really an array. It's an object with sub-objects.
var outputArray = [];
for( var prop in notQuiteArray ) {
outputArray.push({time: prop, percent: notQuiteArray[prop]});
}
where notQuiteArray is the object you were inspecting.

Related

Mapping Array Of Objects By Key

I have two arrays created from a reduce method that searches two existing arrays for dates. It then turns those dates into unique object keys.
The first group is a list of names the second is a set of series of instructions.
The goal is to combine the two arrays that get formed by finding like object keys and adding the matching list object and insert it into the set of instructions with the object key list.
For one it makes an array that looks like :
const listObj = [
{11/20/2020: [{name:'Joe', date:11/20/2020}]},
{11/26/2020 : [{name:'John', date:11/26/2020}]}
]
And this:
const scheduleObj = [
{11/20/2020: {type:'Federal', date:11/20/2020}},
{11/26/2020 : {type:'State', date:11/26/2020}}
]
The final product that i need would look something like:
const scheduleObj = [
{11/26/2020 : {
type: 'State',
list: [{name:'John', date:11/26/2020}]
},
...
]
Where the list is an added key and the array is the array that is associated with the object key
I have used a messy what looks like lodash method to get this to work, but I figure there has to be some sort of mapping I can do.
Any Help Would Be Appreciated
This can be little messy and not failure proof depending on what you have in your listObj or scheduleObj. E.g. repeated date in scheduleObj can lead to a problem using this method, you may have to use another key if the dates are no unique in both lists.
scheduleObj.map((s) => {
// get the first key of the object as the date you're going to group with
const date = Object.keys(s)[0];
// filter the object that matches the date
const listObjFilter = listObj.filter((o) => Object.keys(o)[0] === date);
// get the list for the given date (or empty array if nothing found)
const listForDate = listObjFilter.length ? listObjFilter[0][date] : [];
// build the result object
return {
[date]: {
type: s[date]['type'],
list: listForDate
}
};
})
Note that I'm always considering you have only one key in the objects inside the lists in listObj or scheduleObj.

JavaScript loop, create object, but shows zero in length

I have a javascript method, where I'm trying to group my data by 'date', which works fine.
But when I look at the length of my object it shows, 'zero'.
Is there a better way to do this? and keep the length of the new variable?
groupByDate(snapshot) {
let list = []
this.orders.reduce(function (a, c) {
if(!list[c.date]) {
list[c.date] = [];
}
list[c.date].push(c);
});
this.ordersByDate = list
console.log(list)
}
You are pushing properties into an array. You are not setting the indexes of the array. So you should be using an object and not an array. Your use of reduce is also not correct. You are treating it like a forEach loop.
So use an object and use reduce the way it is supposed to be
let list = this.orders.reduce(function (o, c) {
o[c.date] = o[c.date] || []
o[c.date].push(c)
return o
}, {})
console.log(Object.keys(list).length)
I would use a dictionary (key, values) for that:
list {
date1: [obj1-1, obj1-2, ...],
date2: [obj2-1, obj2-2, ...],
...
}
list = {};
this.orders.forEach(order => {
if (!list.hasOwnProperty(order.date)) {
// If it is the first time we meet this date, create an array with th first element
list[order.date] = [order];
} else {
// We have already meet the date, thus the key exists and so do the array. Add element to array
list[order.date].push(order);
}
});
It seems you have an array and its indexes are the dates. I assume the dates are big numbers (date from 1970 in milliseconds, something like that), which may lead to having a very very big array 99,9% empty. That is why according to me you should use an object and not an array.
Or maybe those are not dates but id's of dates ?

javascript - multidimensional array contains 4 items but length indicates: 0

I made a multidimensional array today which creates 4 new arrays within the first array. when I console.log my array it says that there are 0 items in it, but i do see my 4 arrays each with other items. See the console.log below for a clearer image:
vm.allGroupsInClassifications = [];
datacontext.graph.getAllGroups().then(function (data) {
var groups = [];
// get all clasification names and put them in the array and create a new array
for (var k in vm.classificationNames) {
var groupName = vm.classificationNames[k];
groups[groupName] = new Array();
}
// go through all the groups and sort them based on their classification
for (var i = 0; i < data.length; i++) {
if (data[i].classification != null) {
modifyGroupContent(data[i], groups, 0);
}
else if (data[i].classification == null)
modifyGroupContent(data[i], groups, 1);
}
vm.allGroupsInClassifications = groups;
console.log(vm.allGroupsInClassifications);
any help would be appreciated. Cheers!
Because you have no indexes. groups[groupName] = new Array(); won't add an item to your array, because all your groupName variables are not numbers. And thus you have an array-object-like thing.
If your groupName's were say 0,1,2 and 3, when you console.log the object, you will get the last number+1 (in this case 4).
Here you can access your arrays with the keys - so in this case vm.allGroupsInClassifications['Confidential'] will return your array.
But since you don't have actual numeric indexes, the length of your object-array thing is 0.
Hope you understand
It's because your array is incorrect. You have an array with keys :
[
"Algemeen" : [...],
"Confidential" : [...]
]
This is incorrect, as arrays can't have keys. Javascript being Javascript, it allows you to define it nonetheless, but when you ask for its length, it's quite unable to answer and says 0. It should be an object :
{
"Algemeen" : [...],
"Confidential" : [...]
}
If you really want to keep an array of arrays, remove the keys :
[ [...],[...] ]
Now the length is 2.

JQuery Array To Re-arranged JSON object

I want to covert this javascript Array
[
"Data",
[
"API",
"Apiales",
"Apiaceae",
"Apia",
]
]
to this rearranged json Format
[
{"name":"API","id":"1"},
{"name":"Apiales","id":"1"},
{"name":"Apiaceae","id":"1"},
{"name":"Apia","id":"1"}
]
Thanks
update:
i have tried this
var aNewData =[];
for(i in aData[1]){
var item={};
item.name = aData[1][i];
item.id = "1";
aNewData[i]=item;
}
Where do the ids come from? Test following script, your array is in aData and the result will be in aNewData:
var aNewData = [];
for (var i = 0; i < aData[1].length; i++) {
aNewData.push({
"name": aData[1][i],
"id": 20 + i
});
}
Also see this example.
You might easily transform those data via folding:
var sourceData = ["API","Apiales","Apiaceae","Apia"];
var transformed = sourceData.reduce(function(result, name, index) {
return result.concat({
name: name,
id: 20 + index
});
}, []);
This will give you essentially the same, as the for loop of scessor, but in a more data-centric way.
Think of it like this:
You hold your source data (the array with all those "api*" strings)
You create a fresh resulting array [] (passed as 2nd argument to the reduce), which should be returned as your next result.
Pass an unnamed function to reduce that will be called with 3 arguments, each time it is called, namely result, which is you recently created array, name the value of each of those "api*" strings, and index, which is the index of those strings within the original array.
You look at each of those "api*" strings consecutively and put a new object containing your desired data into it. As result.concat will return the whole array, you just add those
The result array containing all your data will be returned.
But just in case you wanted to be backward compatible with older browsers, I'd recommend using underscore.js for that.

jquery creating two dimensional array

Edit: It appears I was a bit confused on what I was trying to accomplish. For those that took the time to explain this, thank you.
I'm trying to create a two dimensional array in Jquery/Javascript. I've done a decent amount of searching, testing and more searching but i'm unable to find a solution that really makes sense to me. (it's been a very long week already....)
Below is the desired format of the array.
{"product":[{"attribute":"value","attribute":"value"}]}
That's not a 2D array, but rather an object. Also, your product array contains only one object. I think you need something like this:
var obj = {};
obj.product = [];
for(var i=0; i < someObj.length; i++) {
obj.product.push[{"attribute": someObj[i]}]
}
This will produce an array inside the product property:
{"product":[{"attribute":"value"}, {"attribute":"value"}]}
You can't create a two dimensional array in Javascript, arrays can only have one dimension. Jagged arrays, i.e. arrays of arrays, are used instead of two dimensional arrays.
Example:
var a = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
The desired format that you show is neither a two dimensional array nor a jagged array, instead it's an object containing a property that is an array of objects. However, the object in the array has two properties with the same name, so I assume, you meant that as having two objects in the array:
var o = {
product: [
{ attribute: "value" },
{ attribute: "value" }
]
};
You can create an object like that using a literal object like above, or you can create it by adding properties and array items afterwards:
var o = {};
o.product = [];
o.product.push({ attribute: "value" });
o.product.push({ attribute: "value" });
Try this:
{"product":[ [{"attribute":"value"},{"attribute":"value"}]]}
$(".adddiv").each(function(){
tasks = [];
$(".subtasktask"+len).each(function() {
var raw = $(".subtasktask"+len).children().size();
for(var l =0;l
datas.push(milestone);
alert("now show json milestone array : ");
alert(milestone.month + ":" + milestone.title +":" + milestone.task. );
len++
});
This is my solution.
var optionArr = []
optionArr = {"product": [{"id":1, "name":"abc"}, {"name":"value"}]}
var data = optionArr['product'][0]['name']
alert(data)

Categories

Resources