javascript creating data object from 2 arrays [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have 2 arrays already setup within the js:
varDepth:
[0.5, 1.75, 2.38, 2.74, 2.89]
varMins:
[0, 1, 2, 3, 4]
I'm looking to create an object (chartData1) to push and this is the format of the array:
chartData1.push({'x': varDepth[i][0], 'y': varMins[i][1]});
But I cannot get this to work, I think I'm missing the setting up of the object, Any assistance would be greatly appreciated. Thanks!

Since you're trying to create multiple objects who's data are from the same indexes in both arrays; you can;
Loop over one of the arrays (I'm using map() so we can return the created objects into an array)
Add value to a new object
Add value of the other array, on the same index
const depths = [ 0.5, 1.75, 2.38, 2.74, 2.89 ];
const mins = [ 0, 1, 2, 3, 4 ];
let result = depths.map((depth, index) => ({ x: depth, y: mins[index]}))
console.log(result);
[
{
"x": 0.5,
"y": 0
},
{
"x": 1.75,
"y": 1
},
{
"x": 2.38,
"y": 2
},
{
"x": 2.74,
"y": 3
},
{
"x": 2.89,
"y": 4
}
]

Related

sum by object key from array but sum only has word provide in function javascript loadsh [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
i am trying to sum from array by object key but key need to filter by word provided then sum but i don't know how to sum any one can please help me
sum object value only has key.includes('_total') but not key.includes('all_total') and key.includes('cf_total')
let array = [{
"46": 0,
"1592_46_1": 3,
"1592_46_2": 3,
"1592_46_3": 3,
"1592_46_1_total": 3,
"1592_46_1_cf_total": 3,
"1592_46_2_total": 3,
"1592_46_2_cf_total": 3,
"1592_46_3_total": 3,
"1592_46_3_cf_total": 3,
"all_total": 3,
"cf_total": 3,
},
{
"46": 0,
"1593_46_1": 1,
"1593_46_2": 1,
"1593_46_3": 1,
"1593_46_1_total": 1,
"1593_46_1_cf_total": 1,
"1593_46_2_total": 1,
"1593_46_2_cf_total": 1,
"1593_46_3_total": 1,
"1593_46_3_cf_total": 1,
"all_total": 1,
"cf_total": 1,
},
{
"46": 0,
"1594_46_1": 2,
"1594_46_2": 2,
"1594_46_3": 2,
"1594_46_1_total": 2,
"1594_46_1_cf_total": 2,
"1594_46_2_total": 2,
"1594_46_2_cf_total": 2,
"1594_46_3_total": 2,
"1594_46_3_cf_total": 2,
"all_total": 2,
"cf_total": 2,
},
];
my function is
let sum = (word) => {
return _.sumBy(array, function(o)
{
return o.n;
});
};
example sum only value that key include _total word but not include word cf_total and all_total
sum('_total');
return should number 18
You could use reduce for this, and use regex to check whether a number followed by your word is included in each key (to avoid cf_total and all_total):
// Minified for readability
const array = [{46:0,"1592_46_1":3,"1592_46_2":3,"1592_46_3":3,"1592_46_1_total":3,"1592_46_1_cf_total":3,"1592_46_2_total":3,"1592_46_2_cf_total":3,"1592_46_3_total":3,"1592_46_3_cf_total":3,all_total:3,cf_total:3},{46:0,"1593_46_1":1,"1593_46_2":1,"1593_46_3":1,"1593_46_1_total":1,"1593_46_1_cf_total":1,"1593_46_2_total":1,"1593_46_2_cf_total":1,"1593_46_3_total":1,"1593_46_3_cf_total":1,all_total:1,cf_total:1},{46:0,"1594_46_1":2,"1594_46_2":2,"1594_46_3":2,"1594_46_1_total":2,"1594_46_1_cf_total":2,"1594_46_2_total":2,"1594_46_2_cf_total":2,"1594_46_3_total":2,"1594_46_3_cf_total":2,all_total:2,cf_total:2}];
const sum = (word, arr) => {
const regex = new RegExp(`\\d${word}`);
return arr.reduce((total, obj) => {
return total + Object.entries(obj).reduce((sum, [k, v]) => {
return sum + (regex.test(k) ? v : 0);
}, 0);
}, 0);
};
const res = sum('_total', array);
console.log(res); // 18

How do I get the elements in an array with the highest occurrency? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
For example, I have an array like this;
var arr = [0,0,1,2,2,3,4,5,5,5,6,7,7,7,7,8,9,10,10,10]
My goal is to throw unique elements in the array and get the most repeated numbers.
var arr = [7,7,7,7]
How can this be achieved in JavaScript?
var arr = [0, 0, 1, 2, 2, 3, 4, 5, 5, 5, 6, 7, 7, 7, 7, 8, 9, 10, 10, 10]
var uniq = arr.reduce((all, next) => {
var exist = all.find(v => v.key === next)
if (exist) {
exist.count += 1
exist.val.push(next)
} else {
all.push({
key: next,
count: 1,
val: [next]
})
}
return all
}, [])
var max = uniq[0]
uniq.forEach(item => {
if (item.count > max.count) {
max = item
}
})
console.log(max.val)

How to add an array to an array object [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
How do I make object1 to object2? It's a JSON type from an API so I can't just manually put the value of array inside the object. Z is actually var z = [4,5,6]; a completely separate array.
var object1 = {
value:[{
"x": "apple",
"y": [1,2,3]
}]
};
var object2 = {
value:[{
"x": "apple",
"y": [1,2,3],
"z": [4,5,6]
}]
};
You can just access the array and update it:
const updateObjectAtIndex = (arr, index, newData) => {
const clone = [...arr];
const result = {
...clone[index],
...newData
};
clone[index] = result;
return clone;
}
var object1 = {
value:[{
"x": "apple",
"y": [1,2,3]
}]
};
var object2 = {
...object1,
value: updateObjectAtIndex(object1.value, 0, {z: [4, 5, 6]})
}
console.dir(object2)
The Object.assign() method is used to copy the values of all
enumerable own properties from one or more source objects to a target
object. It will return the target object.
var object1 = {
value:[{
"x": "apple",
"y": [1,2,3]
}]
};
var object2 = {
value:[{
"x": "apple",
"y": [1,2,3],
"z": [4,5,6]
}]
};
const object3 = Object.assign(object1, object2);
console.log(object3);

Sort array of objects by quarterly-yearly data in JavaScript [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have an array of data containing objects like below
[
{
"name":"Q1'2016",
"y":0
},
{
"name":"Q2'2016",
"y":0
},
{
"name":"Q3'2016",
"y":0
},
{
"name":"Q4'2015",
"y":0
}
]
I want to sort them based on quarterly, so Q4'2015 should come first, then Q1'2016 and so on.
How can this be acheived?
You can use the sort method and give it a callback to sort your object based on a predicate; in your case, you want to inspect the objects' name property containing your quarter-year information. Since you'll likely have data with different quarters and years, you'll want to map the quarters to month values so you can convert them to year/month dates and compare them that way.
var data = [{
"name": "Q1'2016",
"y": 0
}, {
"name": "Q2'2016",
"y": 0
}, {
"name": "Q3'2016",
"y": 0
}, {
"name": "Q4'2015",
"y": 0
}];
var quarterToMonthMap = {
"Q1": 0,
"Q2": 3,
"Q3": 6,
"Q4": 9
}
function sortByQuarterYear(lhs, rhs) {
var lhsQuarterYear = lhs.name.split("'");
var rhsQuarterYear = rhs.name.split("'");
var lhsDate = new Date(lhsQuarterYear[1], quarterToMonthMap[lhsQuarterYear[0]]);
var rhsDate = new Date(rhsQuarterYear[1], quarterToMonthMap[rhsQuarterYear[0]]);
return lhsDate.getTime() - rhsDate.getTime();
}
document.write(JSON.stringify(data.sort(sortByQuarterYear)));
To sort by year and quarter you can use the following ES6 snippet (you can do the exact same thing using ES5, but I like writing ES6)
input.map((obj, index) => obj.name.split("'").reverse().concat(index)).sort().map(arr => input[arr[2]]);
Let's break this down a bit
input.map((obj, index) => obj.name.split("'").reverse().concat(index))
The map() method creates a new array with the results of calling a provided function on every element in this array.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
Our "provided function" splits the "name" property of each object by the ' character, reverses the resulting array, and adds the current index into the resulting array.
This results in an array that looks like this:
[
["2016", "Q1", 0],
["2016", "Q2", 1],
["2016", "Q3", 2],
["2015", "Q4", 3]
]
Then we call .sort,
The sort() method sorts the elements of an array in place and returns the array. The sort is not necessarily stable. The default sort order is according to string Unicode code points.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
We then end up with an array like this:
[
["2015", "Q4", 3],
["2016", "Q1", 0],
["2016", "Q2", 1],
["2016", "Q3", 2]
]
So we now have an appendix of sorts, notice that the indexes that we threw in there aren't in order. We can use this lack of order to create order.
All we have to do is call map again, this time returning the original object related to the index that we have stored in our temporary arrays.
.map(arr => input[arr[2]]);
When we put it all together and call it, we end up with an array like this:
[
{
name: "Q4'2015",
y: 0
}, {
name: "Q1'2016",
y: 0
}, {
name: "Q2'2016",
y: 0
}, {
name: "Q3'2016",
y: 0
}
]
Here's a demo:
let input = [
{
"name":"Q1'2016",
"y":0
},
{
"name":"Q2'2016",
"y":0
},
{
"name":"Q3'2016",
"y":0
},
{
"name":"Q4'2015",
"y":0
}
];
input = input.map((obj, index) => obj.name.split("'").reverse().concat(index)).sort().map(arr => input[arr[2]]);
console.log(input);
To do the exact same thing in ES5:
input.map(function(obj, index){
return obj.name.split("'").reverse().concat(index);
}).sort().map(function(arr){
return input[arr[2]];
});
Using .sort() with a comparator function, you can easily re-format each value from "Q1'2016" to "2016Q1", allowing a simple alphanumeric comparison because "2016Q1" > "2015Q4".
function sortQuarters(arr) {
function reformat(v) {
return v.replace(/(Q\d)'(\d{4})/, "$2$1");
}
return arr.sort(function(a, b) {
return reformat(a.name).localeCompare(reformat(b.name));
});
}
console.log(sortQuarters([
{ "name":"Q1'2016", "y":0 },
{ "name":"Q3'2016", "y":0 },
{ "name":"Q2'2016", "y":0 },
{ "name":"Q4'2015", "y":0 }
]));
(Note that the reformatting I'm talking about is only within temporary variables used while sorting, it doesn't change the values in the array. Also note that the function I've shown modifies the order of the array passed to it and returns back the same array, it doesn't create a new array.)

How would I convert this to a multi-dimensional array in javascript? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
How would I convert this table to a multi-dimensional array in javascript?
Use an object with the flag names as keys, and arrays of booleans as values.
var table = {
"STAT": [ false, false, false, true, true, false ]
// etc.
How about:
[
[ 'PATIENT_RESULT_IN_RANGE', [ 1, 0, 1 ] ],
[ 'QC_RESULT_IN_RANGE', [ 1, , 0, 1 ] ],
[ 'QC_DUE', [ 0, , , 1, 1, 1 ] ]
// ect.
]
or
{
'PATIENT_RESULT_IN_RANGE': [ 1, 0, 1 ],
'QC_RESULT_IN_RANGE': [ 1, , 0, 1 ],
'QC_DUE': [ 0, , , 1, 1, 1 ]
// ect.
}
I wouldn't use the stars (empty values) though...

Categories