I have object like below
[
{
"value": 14,
"name": "vwap"
},
{
"value": 1,
"name": "yopen"
},
{
"value": 12,
"name": "open"
},
{
"value": 13,
"name": "s3"
},
{
"value": 9,
"name": "fr1"
},
{
"value": 10,
"name": "fr2"
}
]
If my input is 9 , I need output as 1,9 and 10,12,13
If my input is 13 , I need output 1,9,10,12,13 and 14
Output should be 2 seperate objects like { "value": 10, "name": "fr2" } ,Also output should be sorted.
I tried something like below , but it works only for array.
function getVal(array, val, dir) {
for (var i=0; i < array.length; i++) {
if (dir == true) {
if (array[i] > val){
return array[i-1] || 0;
}
} else {
if (array[i] >= val) {
return array[i];
}
}
}
}
You can use filter() and check if given number is less or greater than objects value and use sort() in end
const arr = [ { "value": 14, "name": "vwap" }, { "value": 1, "name": "yopen" }, { "value": 12, "name": "open" }, { "value": 13, "name": "s3" }, { "value": 9, "name": "fr1" }, { "value": 10, "name": "fr2" } ]
function getParts(arr,num,min=0,max=Infinity){
let first = arr.filter(x => num >= x.value && x.value > min && x.value < max).sort((a,b) => a.value-b.value);
let second = arr.filter(x => num < x.value && x.value < max && x.value > min).sort((a,b) => a.value-b.value);
return [first,second];
}
console.log(getParts(arr,9,5,12))
console.log('----------For 13--------------')
console.log(getParts(arr,13))
Another way is to sort() the array first and then slice() it.
const arr = [ { "value": 14, "name": "vwap" }, { "value": 1, "name": "yopen" }, { "value": 12, "name": "open" }, { "value": 13, "name": "s3" }, { "value": 9, "name": "fr1" }, { "value": 10, "name": "fr2" } ]
function getParts(arr,num){
let temp = arr.slice().sort((a,b) => a.value - b.value);
let index = temp.findIndex(x => x.value === num);
return [temp.slice(0,index+1),temp.slice(index)];
}
console.log(JSON.parse(JSON.stringify(getParts(arr,9))))
console.log('----------For 13--------------')
console.log(JSON.parse(JSON.stringify(getParts(arr,13))))
You could take acheck and push the object into the wanted array.
function getParts(value) {
return data.reduce((r, o) => (r[+(o.value > value)].push(o), r), [[], []]);
}
var data = [{ value: 14, name: "vwap" }, { value: 1, name: "yopen" }, { value: 12, name: "open" }, { value: 13, name: "s3" }, { value: 9, name: "fr1" }, { value: 10, name: "fr2" }];
data.sort(({ value: a }, { value: b }) => a - b);
console.log(getParts(9));
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can use an object to store your result, containing both lower and upper parts.
Then, loop your array and compare the value against the input. You'll know where to store your element, in lower or upper part
let datas = [{"value":14,"name":"vwap"},{"value":1,"name":"yopen"},{"value":12,"name":"open"},{"value":13,"name":"s3"},{"value":9,"name":"fr1"},{"value":10,"name":"fr2"}];
function getVal(input)
{
let result =
{
lowerPart: [],
upperPart: []
};
datas.forEach((elem) =>
{
if (elem.value <= input)
result.lowerPart.push(elem);
else
result.upperPart.push(elem);
});
return result;
}
console.log(getVal(9));
console.log(getVal(13));
Using reduce()
var arr = [{"value":14,"name":"vwap"},{"value":1,"name":"yopen"},{"value":12,"name":"open"},{"value":13,"name":"s3"},{"value":9,"name":"fr1"},{"value":10,"name":"fr2"}]
function getVal(arr, find) {
return arr.reduce((acc, i) => {
acc[i.value <= find ? 'l' : 'g'].push(i)
return acc
}, {
l: [],
g: []
})
}
console.log(getVal(arr, 9))
console.log(getVal(arr, 13))
.as-console-wrapper { max-height: 100% !important; top: 0; }
Usage
let res = getVal(arr, 9)
res.l // lowerpart
res.g // greaterpart
You can use filter and sort function for your requirement.
var find = 9;
var left = arr.filter(c=>c.value <= find).sort((a,b) => a.value-b.value);
var right = arr.filter(c=>c.value > find).sort((a,b) => a.value-b.value);
var arr = [
{
"value": 14,
"name": "vwap"
},
{
"value": 1,
"name": "yopen"
},
{
"value": 12,
"name": "open"
},
{
"value": 13,
"name": "s3"
},
{
"value": 9,
"name": "fr1"
},
{
"value": 10,
"name": "fr2"
}
]
var find = 9;
var left = arr.filter(c=>c.value <= find).sort((a,b) => a.value-b.value);
var right = arr.filter(c=>c.value > find).sort((a,b) => a.value-b.value);
console.log('Less than or equal: ' + find);
console.log(left)
console.log('Greater than: ' + find);
console.log(right)
Related
I have an Array object with 3000 objects. Among these 3000 few of them have grade and few object doesn't. Now I want to sum the grades. I'm getting NaN. Could you please guide me what am I doing wrong. Below is the sample code:
const arr=[
{
"name":"Harvey",
"grade":3
},
{
"name":"Pamela",
},
{
"name":"Scott",
"grade":4
},
{
"name":"Joshua",
"grade":5
},{
"name":"Rachel",
},{
"name":"Harvey",
"grade":3
},
]
let classTotal = arr.reduce(function (previousValue, currentValue) {
return {
grade: (previousValue.grade + currentValue.grade)
}
})
console.log(classTotal) //NaN
Also tried the following:
let classTotal=arr.reduce((accum, item) => accum + item.total, 0)
console.log(classTotal) // Same NaN
If either of the .grade values is itself not a number (such as undefined) then it will break the ongoing calculations. One approach could be to default it to 0 when no value is present. So instead of currentValue.grade you might use (currentValue.grade ?? 0). For example:
const arr=[
{
"name":"Harvey",
"grade":3
},
{
"name":"Pamela",
},
{
"name":"Scott",
"grade":4
},
{
"name":"Joshua",
"grade":5
},
{
"name":"Rachel",
},
{
"name":"Harvey",
"grade":3
},
];
let classTotal = arr.reduce(function (previousValue, currentValue) {
return {
grade: (previousValue.grade + (currentValue.grade ?? 0))
};
});
console.log(classTotal);
NaN is "Not a valid Number" you have some entries missing grade you should run filter to filter them out before your reduce
const arr = [{
"name": "Harvey",
"grade": 3
},
{
"name": "Pamela",
},
{
"name": "Scott",
"grade": 4
},
{
"name": "Joshua",
"grade": 5
}, {
"name": "Rachel",
}, {
"name": "Harvey",
"grade": 3
},
]
let classTotal = arr.filter(function(element) {
return element.grade
}).reduce(function(previousValue, currentValue) {
return {
grade: (previousValue.grade + currentValue.grade)
}
})
console.log(classTotal)
Or, you can add a 0 for example for the elements who does not have a grade:
const arr = [{
"name": "Harvey",
"grade": 3
},
{
"name": "Pamela",
},
{
"name": "Scott",
"grade": 4
},
{
"name": "Joshua",
"grade": 5
}, {
"name": "Rachel",
}, {
"name": "Harvey",
"grade": 3
},
]
let classTotal = arr.reduce(function(previousValue, currentValue) {
return {
grade: (previousValue.grade + (currentValue.grade || 0))
}
})
console.log(classTotal)
I have a nested json array and I am trying to get the maximum value of the points attribute in this array.
data = {
"name": "KSE100",
"children": [
{
"name": "TECHNOLOGY & COMMUNICATION",
"children": [
{
"name": "TRG",
'points': -21
},
{
"name": "SYS",
},
]
},
{
"name": "OIL",
"children": [
{
"name": "PPL",
'points': 9
},
{
"name": "PSO",
'points': -19
},
]
},
]
}
I want the max value of points from under the children sections. I mean from under technology and oil sectors.
What I've done so far:
var max;
for (var i in data.children.length) {
for (var j in data.data[i]) {
var point = data.data[i].children[j]
}
}
Try the following:
data = {
"name": "KSE100",
"children": [
{
"name": "TECHNOLOGY & COMMUNICATION",
"children": [
{
"name": "TRG",
'points': -21
},
{
"name": "SYS",
},
]
},
{
"name": "OIL",
"children": [
{
"name": "PPL",
'points': 9
},
{
"name": "PSO",
'points': -19
},
]
},
]
}
var array = [];
for (var first of data.children) {
for (var second of first.children) {
if(second.points != undefined)
{
array.push(second);
}
}
}
var maximumValue = Math.max.apply(Math, array.map(function(obj) { return obj.points; }));
console.log(maximumValue);
you can use the reduce method on the array object to do this
const maxValues = []
data.children.forEach(el => {
if (el.name === 'OIL' || el.name === 'TECHNOLOGY & COMMUNICATIO'){
const max = el.children.reduce((current, previous) => {
if (current.points > previous.points) {
return current
}
}, 0)
maxValues.append({name: el.name, value: max.points})
}
})
This will give you an array of the objects with the name and max value.
First you can convert your object to a string through JSON.stringify so that you're able to use a regular expression
(?<=\"points\":)-?\\d*
To matchAll the values preceded by the pattern \"points\": that are or not negative values. After it, convert the result to a array through the spread operator ... and then reduce it to get the max value.
const data = {name:"KSE100",children:[{name:"TECHNOLOGY & COMMUNICATION",children:[{name:"TRG",points:-21},{name:"SYS"}]},{name:"OIL",children:[{name:"PPL",points:9},{name:"PSO",points:-19}]}]};
console.log(
[ ...JSON.stringify(data).matchAll('(?<=\"points\":)-?\\d*')]
.reduce((acc, curr) => Math.max(curr, acc))
)
I wasn't 100% sure, what your exact goal is, so I included a grouped max value and and overall max value with a slight functional approach.
Please be aware that some functionalities are not working in older browsers i.e. flatMap. This should anyways help you get started and move on.
const data = {
name: "KSE100",
children: [
{
name: "TECHNOLOGY & COMMUNICATION",
children: [
{
name: "TRG",
points: -21,
},
{
name: "SYS",
},
],
},
{
name: "OIL",
children: [
{
name: "PPL",
points: 9,
},
{
name: "PSO",
points: -19,
},
],
},
],
};
const maxPointsByGroup = data.children.reduce(
(acc, entry) => [
...acc,
{
name: entry.name,
max: Math.max(
...entry.children
.map((entry) => entry.points)
.filter((entry) => typeof entry === "number")
),
},
],
[]
);
console.log("grouped max:", maxPointsByGroup);
const overallMax = Math.max(
...data.children
.flatMap((entry) => entry.children.flatMap((entry) => entry.points))
.filter((entry) => typeof entry === "number")
);
console.log("overall max:", overallMax);
I have a JSON database with objects. Each one has properties with a specific assigned value: a, b or c.
[
{
"id": 1,
"category": "a"
},
{
"id": 2,
"category": "b"
},
{
"id": 3,
"category": "c"
},
{
"id": 4,
"category": "a"
},
{
"id": 5,
"category": "a"
},
{
"id": 5,
"category": "b"
}
]
I want to display something like:
There is a total of 6 items: a x 3, b x 2 and c x 1.
I know I have to use objectsinmyjsondatabase.length to get the total.
I'm wondering how is it possible to get the length (number) of objects that have a specific value?
Define a function:
getCount(character) {
return this.objects.filter(obj => obj.category === character).length;
}
and the call it as:
this.getCount('a');
One way to solve your problem is to use map-reduce. Here is a quick solution. Hope that will solve your problem.
var data = [
{
"id": 1,
"category": "a"
},
{
"id": 2,
"category": "b"
},
{
"id": 3,
"category": "c"
},
{
"id": 4,
"category": "a"
},
{
"id": 5,
"category": "a"
},
{
"id": 5,
"category": "b"
}
];
// First get list of all categories
var categories = data.map(function(x) { return x["category"]; });
// Count no of items in each category
var countByCategories = categories.reduce(function(x, y) {
if (typeof x !== "object") {
var reduced = {};
reduced[x] = 1;
reduced[y] = 1;
return reduced;
}
x[y] = (x[y] || 0) + 1;
return x;
});
// Final build string that you want
var categoryStrings = [];
for (var category in countByCategories) {
categoryStrings.push(category + ' x ' + countByCategories[category]);
}
var msg = 'There is a total of ' + categories.length + ' items: ';
if (categoryStrings.length > 2) {
msg = categoryStrings.slice(0, -1).join(', ');
msg += ' and ' + categoryStrings.slice(-1);
} else {
msg = categoryStrings.join(', ');
}
// print results
console.log(msg);
You easily can count objects which have specific value like this
let objects = [
{
"id": 1,
"category": "a"
},
{
"id": 2,
"category": "b"
},
{
"id": 3,
"category": "c"
},
{
"id": 4,
"category": "a"
},
{
"id": 5,
"category": "a"
},
{
"id": 5,
"category": "b"
}
];
var filtered = new Array();
objects.filter(function (t) {
var found = filtered.some(function (el, index) {
if (false == (t.category === el.category)) {
return false;
}
filtered[index].count = filtered[index].count + 1;
return true;
}, filtered);
if (false === found) {
filtered.push({category: t.category, count: 1});
}
}, filtered);
console.log('There is a total of ' + objects.length + ' items: '
+ filtered.map(function (t) {
return t.category + ' x ' + t.count;
})
);
This question already has answers here:
reduce array to a by grouping objects with same property
(2 answers)
Closed 6 years ago.
I have an object as:
[
{
"DATA": "2016-01-22",
"TOTAL": "7"
},
{
"DATA": "2016-01-25",
"TOTAL": "3"
},
{
"DATA": "2016-01-26",
"TOTAL": "1"
},
{
"DATA": "2016-01-27",
"TOTAL": "2"
},
{
"DATA": "2016-01-22",
"TOTAL": "1"
},
{
"DATA": "2016-01-25",
"TOTAL": "1"
},
{
"DATA": "2016-01-27",
"TOTAL": "1"
},
...
]
How can I shrink it down to something like below, this is, concatenate/join the TOTAL keys where the date is the same and fill with 0 in case the date doesn't repeat?:
[
{
"DATA": "2016-01-22",
"TOTAL": ["7", "1"]
},
{
"DATA": "2016-01-25",
"TOTAL": ["3", "1"]
},
{
"DATA": "2016-01-26",
"TOTAL": ["1", "0"]
},
{
"DATA": "2016-01-27",
"TOTAL": ["2", "1"]
}
]
I've been trying with this block of code, but can't get TOTAL keys all the same dimension - filled with zeros would be fine.
var output = [];
d.forEach(function(value) {
var existing = output.filter(function(v, i) {
return v.DATA == value.DATA;
});
if (existing.length) {
var existingIndex = output.indexOf(existing[0]);
output[existingIndex].TOTAL = output[existingIndex].TOTAL.concat(value.TOTAL);
} else {
if (typeof value.TOTAL == 'string')
value.TOTAL = [value.TOTAL];
output.push(value);
}
});
console.log(JSON.stringify(output, null, 4));
var someData = [] // <- your instantiated array in question.
var transformedData = [];
var highestCount = 0;
someData.forEach(x => {
var foundIndex = transformedData.findIndex((ele) => ele.DATA === x.DATA);
if (foundIndex < 0) {
transformedData
.push({DATA : x.DATA, TOTAL : [x.TOTAL]});
} else {
transformedData[foundIndex]
.TOTAL.push(x.TOTAL);
var currentCountAtIndex = transformedData[foundIndex].TOTAL.length;
if (highestCount < transformedData[foundIndex].TOTAL.length) highestCount = currentCountAtIndex;
}
});
// fill any indicies in array that are lower than the highest count with 0
transformedData
.forEach(x => {
if (x.TOTAL.length < highestCount) {
while(x.TOTAL.length < highestCount) {
x.TOTAL.push(0);
}
}
});
It could be as simple as this:
var result = {};
var test = [
{
"DATA": "2016-01-22",
"TOTAL": "7"
},
{
"DATA": "2016-01-25",
"TOTAL": "3"
},
{
"DATA": "2016-01-26",
"TOTAL": "1"
},
{
"DATA": "2016-01-27",
"TOTAL": "2"
},
{
"DATA": "2016-01-22",
"TOTAL": "1"
},
{
"DATA": "2016-01-25",
"TOTAL": "1"
},
{
"DATA": "2016-01-27",
"TOTAL": "1"
}];
console.log("test array: ", test);
var len = 0,
sorted;
// Flatten the object.
test.forEach( d => {
result[d.DATA] == undefined ? result[d.DATA] = [d.TOTAL] : result[d.DATA].push(d.TOTAL);
});
// Sort so we get the max length to know how many zeros to add.
sorted = Object.keys(result).sort( (k, b) => {
return result[k].length - result[b].length;
});
// Max length from the sorted array.
len = result[sorted[sorted.length - 1]].length;
// push zeros
Object.keys(result).forEach( k => {
if(result[k].length < len){
for(var i = result[k].length; i < len; i++){
result[k].push("0");
}
}
});
console.log("result: ", result);
Below are my two arrays .I want to compare them and the resultant array should contain the updated values.Id's are common..
The arrays spans to n levels ie., there is no fixed levels..
The first array ie., the array before updation..
var parentArray1=[
{
"id": 1,
"name": "test",
"context": [
{
"id": 1.1,
"name": "test 1.1"
}
]
},
{
"id": 2,
"name": "test"
},
{
"id": 3,
"name": "test",
"context": [
{
"id": 3.1,
"name": "test 3.1"
}
]
},
{
"id": 4,
"name": "test"
}
]
The operations that i performed are
1.Adding a new Item
2.Updating an existing item
As a result of these two operations the changed values I will be getting in a different array..
ie.,
var changedArray=
[
{
"id": 1,
"name": "test1",
"context": [
{
"id": 1.1,
"name": "Changed test 1.1"
}
]
},
{
"id": 5,
"name": "test5"
}
]
Now I have written a generic function that loops through the parentArray1 and using the unique propertiesI need to either add a new item,if the item is there in the changedArray or update an existing item at any level
The resultant array should be ..
[
{
"id": 1,
"name": "test",
"context": [
{
"id": 1.1,
"name": "Changed test 1.1"
}
]
},
{
"id": 2,
"name": "test"
},
{
"id": 3,
"name": "test",
"context": [
{
"id": 3.1,
"name": "test 3.1"
}
]
},
{
"id": 4,
"name": "test"
},
{
"id": 5,
"name": "test5"
}
]
Generic function:
compareArray(parentArray1, changedArray, ["id"]);
function compareArray(array1, array2, propertyArray) {
var newItem = new Array();
array2.map(function(a1Item) {
array1.map(function(a2Item) {
/ If array loop again /
if (a2Item.constructor === Array) {
compareArray(a2Item, a1Item)
} else {
/ loop the property name to validate /
propertyArray.map(function(property) {
if (a2Item[property]) {
if (a2Item[property] === a1Item[property]) {
a2Item = a1Item
} else {
var isAvailable = _.find(newItem, function(item) {
return item[property] === a1Item[property]
})
if (!isAvailable) {
newItem.push(a1Item);
}
}
}
})
}
});
});
/ Insert the new item into the source array /
newItem.map(function(item) {
array1.push(item);
});
console.log("After Compare : " + array1);
}
I suggest to use a temporary object for the reference to the id and update if exist or push if not exist.
var parentArray1 = [{ "id": 1, "name": "test", "context": [{ "id": 1.1, "name": "test 1.1" }] }, { "id": 2, "name": "test" }, { "id": 3, "name": "test", "context": [{ "id": 3.1, "name": "test 3.1" }] }, { "id": 4, "name": "test" }],
changedArray = [{ "id": 1, "name": "test1", "context": [{ "id": 1.1, "name": "Changed test 1.1" }] }, { "id": 5, "name": "test5" }];
function insert(array, data) {
function iter(array) {
array.forEach(function (a) {
if (!('id' in a)) {
return;
}
if (o[a.id] !== a) {
o[a.id] = a;
}
Object.keys(a).forEach(function (k) {
Array.isArray(a[k]) && iter(a[k]);
});
});
}
var o = {};
iter(array);
data.forEach(function (a) {
if (o[a.id]) {
Object.keys(a).forEach(function (k) {
o[a.id][k] = a[k];
});
return;
}
array.push(a);
});
}
insert(parentArray1, changedArray);
document.write('<pre>' + JSON.stringify(parentArray1, 0, 4) + '</pre>');
This is what I came up with:
function sameKeys(o1, o2, keys) {
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (!o1.hasOwnProperty(key) || !o2.hasOwnProperty(key))
throw 'compared objects do not have the key ' + key;
if (o1[key] !== o2[key])
return false;
}
return true;
}
function isNothing(o) {
return typeof(o) === 'undefined' || o === null;
}
// this does not work if objects have functions as properties
function clone(o) {
if (isNothing(o))
return o;
return JSON.parse(JSON.stringify(o));
}
function extend(o1, o2, keys) {
if (isNothing(o2))
return;
if (isNothing(o1))
throw ('first parameter cannot be empty');
if (typeof(o1) != 'object' || typeof(o2) != 'object')
throw ('extend only works on objects');
Object.keys(o2).forEach(function (key) {
var newVal = o2[key];
if (o1.hasOwnProperty(key)) {
if (isNothing(newVal)) {
delete o1[key];
} else
if (Array.isArray(newVal)) {
compareArray(o1[key], newVal, keys);
} else {
switch (typeof(newVal)) {
case 'object':
extend(o1[key], newVal, keys);
break;
case 'boolean':
case 'number':
case 'string':
o1[key] = newVal;
break;
default:
throw 'not supported property type: ' + typeof(newVal);
}
}
} else {
o1[key] = clone(newVal);
}
});
}
function removeFromArray(arr, ids, keyArray) {
var indexes = [];
var it1s = arr.forEach(function (it, idx) {
if (sameKeys(ids, it, keyArray)) {
indexes.push(idx);
} else {
Object.keys(it).forEach(function (key) {
var newVal = it[key];
if (Array.isArray(newVal)) {
removeFromArray(it[key], ids, keyArray);
}
});
}
});
if (indexes.length) {
if (indexes.length > 1)
throw 'found multiple possible objects for the same key combination'
arr.splice(indexes[0], 1);
}
}
function compareArray(a1, a2, keyArray) {
a2.forEach(function (it2) {
var it1s = a1.filter(function (it) {
return sameKeys(it2, it, keyArray);
});
var it1;
if (!it1s.length) {
it1 = clone(it2);
a1.push(it1);
} else {
if (it1s.length > 1)
throw 'found multiple possible objects for the same key combination'
it1 = it1s[0];
extend(it1, it2, keyArray);
}
if (it2.removedIds) {
it2.removedIds.forEach(function (ids) {
removeFromArray(a1, ids, keyArray);
});
}
});
}
Use it with compareArray(parentArray1,changedArray,['id']);
Note that it would not work with objects that contain functions. Also, if the arrays would be large, perhaps a better solution is to sort both arrays by key, then always look from the last found object up. That's all I got for now.
Updated it with some concepts from Nina and some clearing of the code.
As I understood it, you only want to add properties. So extend({a: {b: 2}},{a:{c:3}}) will result in {a: {b:2,c:3}}. If this is not what you wanted, let me know.
I also added functionality for removing ids. If any of the objects in the array contains a removedIds array of the form [{id: 4},{id: 5}] then the items with those ids will be removed from the original array.
Slight modification on code, to satisfy your conditions. Try it!
function compareArray(originalArray, destinationArray, propertyArray) {
var newItem = new Array(), processedItem = new Array();
for (var i = 0; i < originalArray.length; i++) {
var sourceElement = originalArray[i];
for (var j = 0; j < destinationArray.length; j++) {
var destinationElement = destinationArray[j];
var isUpdated = false;
if (sourceElement.constructor === Array) {
compareArray(sourceElement, destinationElement, propertyArray);
} else {
/* loop the property name to validate */
propertyArray.map(function(property) {
if (sourceElement[property]) {
if (sourceElement[property] === destinationElement[property]) {
originalArray[i] = _.clone(destinationElement);
isUpdated = true;
return;
} else {
var isAvailable = _.find(newItem, function(item) {
return item[property] === destinationElement[property];
});
if (!isAvailable) {
var isAlreadyProcessed = _.find(processedItem, function(item) {
return item[property] === destinationElement[property];
});
if(!isAlreadyProcessed){
newItem.push(destinationElement);
}
}
}
}
});
}
if (isUpdated === true) {
break;
}
}
processedItem.push(sourceElement);
}
newItem.map(function(item) {
originalArray.push(item);
});
return originalArray;
}