I'm currently trying to generate a new order of numbers from a current array with numbers from 1 - 10.
For example, I have arrary like this:
data = [
{
0: 1,
1: 2,
2: 3,
3: 4,
4: 5,
5: 6
},
{
0: 1,
1: 2,
2: 3,
3: 4,
4: 5,
5: 8
}
]
And i'm trying to generate a new order from this array from numbers from 1 - 10.
For example:
I want it to generate a new order like this:
0: 1,
1: 2,
2: 3,
3: 4,
4: 5,
5: 7 (The new number)
Where it checks the order of the array, and make a new order with numbers from 1 - 10
First thing to do is to create an object with the total values. We can accomplish this by looping over each object in the array and add each value to a new object. For this we can use the reduce method on the data array.
After that loop over the object with the totals and divide each value with the amount of objects that are present in the data array.
Use Math.round() to round each value to the nearest whole number.
const data = [{
0: 1,
1: 2,
2: 3,
3: 4,
4: 5,
5: 6
},
{
0: 1,
1: 2,
2: 3,
3: 4,
4: 5,
5: 8
}
];
function getDataTotal(data) {
const totalObject = data.reduce((total, curObj) => {
for (const key of Object.keys(curObj)) {
total[key] = total[key]
? total[key] + curObj[key]
: curObj[key];
}
return total;
}, {});
const averageObject = {};
for (const [key, value] of Object.entries(totalObject)) {
averageObject[key] = Math.round(value / data.length);
}
return averageObject;
}
const averageObject = getDataTotal(data);
console.log(averageObject);
Make sure you have the same keys on both objects.
const data = [
{0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6},
{0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 8},
]
getAverageValueOfMappingElements() {
const keys = Object.keys(data[0])
return [...keys].map(key => {
return (data[0][key] + data[1][key]) / 2
})
}
Related
I have an Excel sheet which has 500 rows. I am trying to get the rows from 101 to 200.
I have searched in google, and I have found an example to get starting rows, e.g. 1 to 100 or 1 to 1000, or even 1 to any number.
But I haven't found any code to get rows from mth row to nth row (Here 'm' and 'n' can be any number eg m=101 to n=200)
Below is the code which I have found to get first 100 rows:
let workbook = XLSX.readFile('./files/uploaded_files/testfile.xlsx', {sheetRows: 100})
const wsname = workbook.SheetNames[0];
const ws = workbook.Sheets[wsname];
var exceldata = XLSX.utils.sheet_to_json(ws);
Even if there is any other module to get the rows in between, I would like to know if there is any ?
Using a smaller example of:
There are several options:
You can use your current approach and slice the array returned from sheet_to_json e.g.
// option 1
const maxRow = 6;
const minRow = 3;
const wb = XLSX.readFile("./Book1.xlsx", {sheetRows: maxRow});
const ws = wb.Sheets[wb.SheetNames[0]];
let data = XLSX.utils.sheet_to_json(ws);
data = data.slice(minRow <= 2 ? 0 : minRow - 2);
console.log(data);
It's minRow - 2 to account for 1 row being headers and that the other 1 is to include row 3, not exclude it. This produces:
[
{ a: 4, b: 5, c: 6 },
{ a: 7, b: 8, c: 9 },
{ a: 10, b: 11, c: 12 },
{ a: 13, b: 14, c: 15 }
]
Another option is to combine use of the range and header (see here) options. range allows you to control what range is considered by sheet_to_json and header is used to define the keys used in the output array of objects.
You can use this after importing the whole file or continue to use the sheetRows option as well e.g.:
// option 2
const importRange = "A3:F6";
const headers = ["a", "b", "c"];
const wb = XLSX.readFile("./Book1.xlsx"); // not using sheetRows
const ws = wb.Sheets[wb.SheetNames[0]];
const data = XLSX.utils.sheet_to_json(ws, {range: importRange, header: headers});
console.log(data);
Which produces:
[
{ a: 4, b: 5, c: 6 },
{ a: 7, b: 8, c: 9 },
{ a: 10, b: 11, c: 12 },
{ a: 13, b: 14, c: 15 }
]
Noting that if you omit the headers option then the output is:
[
{ '4': 7, '5': 8, '6': 9 },
{ '4': 10, '5': 11, '6': 12 },
{ '4': 13, '5': 14, '6': 15 }
]
Because the values in row 3 become the new default headers (which I think you probably don't want).
Finally, if you don't know the headers in advance you can just get an array of arrays and figure the headers out later:
// option 3
const importRange = "A3:F6";
const headers = 1;
const wb = XLSX.readFile("./Book1.xlsx"); // not using sheetRows
const ws = wb.Sheets[wb.SheetNames[0]];
const data = XLSX.utils.sheet_to_json(ws, {range: importRange, header: headers});
console.log(data);
Which produces:
[
[ 4, 5, 6 ],
[ 7, 8, 9 ],
[ 10, 11, 12 ],
[ 13, 14, 15 ]
]
I have two jsons:
first: {
"a": 1,
"b": 9,
"c": 12,
"d": 5
}
and
second: {
"a": 7,
"e": 8,
"b": 11,
"f": 7
}
and i want to create chartjs bar that include both json (with two datasets).
The labels should be 'a', 'b', 'c', 'd', 'e', 'f' and the "first" dataset's data will be: 1, 9, 12, 5, 0, 0. The "second" dataset's data will be: 7, 11, 0, 0, 8, 7.
My code right now:
var barChartData = {
labels: Object.keys(first),
datasets:[
{
label:'first',
data: Object.values(first)
},
{
label: 'second',
data: Object.values(second)
}]
};
window.myBar = new Chart(document.getElementById("barChart").getContext("2d"),
{
type:'bar',
data: barChartData
});
The problem is that i want the labels to be from the keys of both 'first' and 'second' jsons and not just from the 'first' and also that the values will be suitable to the keys.
Is there any simple way to do this?
It looks like you want both objects to have the same keys but with a value of zero when the keys aren't defined. There are several ways to do this. One option would be to make a list of the combined keys of both objects and just loop over them setting the object's value to 0 if the key doesn't exist:
let first = {"a": 1,"b": 9,"c": 12,"d": 5 }
let second = {"a": 7,"e": 8,"b": 11,"f": 7}
Object.keys(Object.assign({}, first, second)) // get combined keys
.forEach(k => {
if (!first.hasOwnProperty(k)) first[k] = 0; // set 0 if key is not in object
if (!second.hasOwnProperty(k)) second[k] = 0;
})
console.log(first, second)
Let's say we have an Array which contains arrays inside:
[
["2000-01-01", "xyz1#gmail.com", 1, 9, 338],
["2000-01-01", "xyz2#yahoo.com", 1, 2, 159],
["2000-01-01", "xyz3#yahoo.com", 1, 5, 462],
["2000-01-01", "xyz4#yahoo.com", 1, 6, 417],
["2000-01-01", "xyz5#gmail.com", 1, 3, 156],
["2000-01-01", "xyz6#gmail.com", 1, 8, 414],
]
I want to get top 2 based on the last column i.e.
["2000-01-01", "xyz3#yahoo.com", 1, 8, 462],
["2000-01-01", "xyz4#yahoo.com", 1, 6, 417],
We can use Array.filter but not really sure how to in this situation.
You could sort descending by the element at index 4 and take the first two elements.
This propposal features a destructuring assignment, where an array is taken for destructuring and the property 4 is taken and renamed to a rsp. to b.
Example:
vvv
{ 4: a } = ["2000-01-01", "xyz1#gmail.com", 1, 9, 338]
^
Result
a = 338
var array = [["2000-01-01", "xyz1#gmail.com", 1, 9, 338], ["2000-01-01", "xyz2#yahoo.com", 1, 2, 159], ["2000-01-01", "xyz3#yahoo.com", 1, 5, 462], ["2000-01-01", "xyz4#yahoo.com", 1, 6, 417], ["2000-01-01", "xyz5#gmail.com", 1, 3, 156], ["2000-01-01", "xyz6#gmail.com", 1, 8, 414]],
top2 = array.sort(({ 4: a }, { 4: b }) => b - a).slice(0, 2);
console.log(top2);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Without sorting:
function getTopTwo(array){
let first = {4: - Infinity}, second = { 4: - Infinity};
for(const el of array){
if(el[4] > first[4]){
second = first;
first = el;
} else if(el[4] > second[4]){
second = el;
}
}
return [first, second];
}
I want to merge 2 object with same key, value from 2 array, something like this:
var arr1 = [
{ a: "a", 1: 1, 2: 2 },
{ a: "b", 1: 1, 2: 3 }
];
var arr2 = [
{ a: "a", 3: 123 },
{ a: "b", 3: 4411 }
];
var arr3 = _.map(arr1, function(a1) {
var a3 = {};
_.map(arr2, function(a2) {
if (a1.a == a2.a) {
a3 = _.extend(a1, a2);
}
})
return a3
});
result:
arr3 = [
{ '1': 1, '2': 2, '3': 123, a: 'a' },
{ '1': 1, '2': 3, '3': 4411, a: 'b' }
]
Does it look stupid? Are there any others ways to do this?
Thanks for reading.
Use a lodash chain to concat the arrays, group similar objects, and then merge each group to a single object:
var arr1 = [{ a: "a", 1: 1, 2: 2 }, { a: "b", 1: 1, 2: 3 }];
var arr2 = [{ a: "a", 3: 123 }, { a: "b", 3: 4411 }];
var result = _(arr1)
.concat(arr2) // concat the 2nd array
.groupBy('a') // group by the identical key
.map(_.spread(_.curry(_.merge, {}))) // left currey merge to to create a new empty object, and spread the group as parameters
.value();
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
With ES6 you can use Array#reduce to collect the similar objects in a Map, then get the Map#values iterator, and use the spread syntax to convert to an array:
const arr1 = [{ a: "a", 1: 1, 2: 2 }, { a: "b", 1: 1, 2: 3 }];
const arr2 = [{ a: "a", 3: 123 }, { a: "b", 3: 4411 }];
const result = [...arr1.concat(arr2) // concat the arrays
.reduce((m, o) => m.set(o.a, Object.assign(m.get(o.a) || {}, o)), // use a map to collect similar objects
new Map()
).values()]; // get the values iterator of the map, and spread into a new array
console.log(result);
you can do
var arr1 = [
{ a: "a", 1: 1, 2: 2 },
{ a: "b", 1: 1, 2: 3 }
];
var arr2 = [
{ a: "a", 3: 123 },
{ a: "b", 3: 4411 }
];
let result = arr1.map((e) => {
for(let element of arr2){
if(e.a == element.a) Object.assign(e, element);
}
return e;
});
console.log(result);
I have a hash like below
a ={
0: [0, "A9"],
2: [0, "A9.4"],
8: [0, "A9.1"],
6: [1, "A9.5"],
5: [0, "A9.2"],
7: [2, "A9.3"]
};
I need a sorted array corresponding to the second element of the array of every Value.
i.e if my array is in the form of a = {key: [value_1_integer, value_2_string]}
I need to sort my hash by value_2_string so result array is
result = [0, 8, 5, 7, 2, 6]
You can apply Array#sort on the keys with a callback which takes the second elements of the property for sorting.
var object = { 0: [0, "A9"], 2: [0, "A9.4"], 8: [0, "A9.1"], 6: [1, "A9.5"], 5: [0, "A9.2"], 7: [2, "A9.3"] },
keys = Object.keys(object).sort(function (a, b) {
return object[a][1].localeCompare(object[b][1]);
});
console.log(keys);