Sorting array of objects including negative values [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 5 months ago.
The community is reviewing whether to reopen this question as of 4 months ago.
Improve this question
I have here the data
var sampleArray = [
{ "Rating 1": -75 },
{ "Rating 2": -70 },
{ "Rating 3": 98 },
{ "Rating 4": -88 },
{ "Rating 5": 29 },
];
I want to sort it to output the following
Highest rating
Lowest rating
Rating that is near 0 (if there are 2 results, the positive will be chosen example:-1,1 then 1 will be chosen)
I'm stuck on getting the second value only which is the rating. I've tried the following codes to check if I can get the rating, but it shows the entire value of array 0
function topProduct(productProfitArray) {
return productProfitArray[0];
}

You can do this with reduce and a bit of logic to keep track of your min,max and diff from zero items
var sampleArray = [
{ "Rating 1": -75 },
{ "Rating 2": -70 },
{ "Rating 3": 98 },
{ "Rating 4": -88 },
{ "Rating 5": 29 },
];
var result = sampleArray.reduce( (acc,i) => {
var val= Object.values(i)[0];
if(val > acc.max)
{
acc.maxEntry = i;
acc.max = val;
}
if(val < acc.min)
{
acc.minEntry = i;
acc.min = val;
}
var diffFromZero = Math.abs(0-val);
if(diffFromZero < acc.diffFromZero)
{
acc.diffFromZero = diffFromZero;
acc.diffEntry = i;
}
return acc;
},{min:Number.POSITIVE_INFINITY, max:Number.NEGATIVE_INFINITY,diffFromZero:Number.POSITIVE_INFINITY});
console.log("min",result.minEntry);
console.log("max",result.maxEntry);
console.log("closeToZero",result.diffEntry);

Related

How we can replace the keys of an Object with new key? [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 1 year ago.
Improve this question
I have an object like below
[
{
"day" : "monday",
"value": 1
},
{
"day" : "tuesday",
"value": 2
},
...
]
Is there any native javascript way to replace the key with a new key. Here I need to replace the "day" & "value" with "x" & "y" respectively. (like below)
[
{
"x" : "monday",
"y": 1
},
{
"x" : "tuesday",
"y": 2
},
...
]
you can use map and inside the call back create a new object and modify it as required. Then return this object
const data = [{
"day": "monday",
"value": 1
},
{
"day": "tuesday",
"value": 2
}
];
const newData = data.map((item) => {
const obj = {};
for (let keys in item) {
if (keys === 'day') {
obj['x'] = item[keys]
}
if (keys === 'value') {
obj['y'] = item[keys]
}
};
return obj
});
console.log(newData)

How to get keys from json object 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 1 year ago.
Improve this question
I have a json file:
[
{
"name": "Cocktail 1",
"ingredients": {
"rum": 12,
"coke": 48
}
}, {
"name": "Cocktail 2",
"ingredients": {
"gin": 24,
"tonic": 60
}
}]
Now I want to get a list of the keys of each "name" object. At the end there should be ths list
var mydata[0] = rum
var mydata[1] = coke
var mydata[2] = gin
var mydata[3] = tonic
and save it into an array.
What i have tried
var mydata = JSON.parse("jsonstring").ingredients;
hope this is understanable?
for each data in the array (map)
you want the ingredient part (.ingredients),
extract the keys (Object.keys)
and flatten the array (.flat())
array.map(a => a.ingredients).map(a => Object.keys(a)).flat();
You may prefer loop style. the only difference is flattening occurs with ... operator.
var results = [];
for (let a of array) {
results.push(...Object.keys(a.ingredients))
}
My proposition is :
'use strict'
const array = [
{
"name": "Cocktail 1",
"ingredients": {
"rum": 12,
"coke": 48
}
},
{
"name": "Cocktail 2",
"ingredients": {
"gin": 24,
"tonic": 60
}
}
]
const mydata = array.map((val) => {
return Object.keys(val.ingredients);
}).flat();
console.log(mydata)
// expected output: Array ["rum", "coke", "gin", "tonic"]
// Now you can get :
var mydata[0] = rum
var mydata[1] = coke
var mydata[2] = gin
var mydata[3] = tonic
Hope that help you? Thank

Summarize data in array of objects by common date [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 2 years ago.
Improve this question
This is my data,
"time" is number
[
{
"time": 202007150800,
"count": 10
},
{
"time": 202007160700,
"count": 11
},
{
"time": 202007160900,
"count": 12
}
]
How do I use "time" group data from 8 o'clock yesterday to 8 o'clock today and sum "count"
,For example, 7/15 data is 7/15 08:00 - 7/16 07:00
like this:
[
{
"time": 20200715,
"count": 21
},
{
"time": 20200716,
"count": 12
}
]
Try this function
function mapData(data) {
let result = [];
data.forEach(element => {
let t = element.time + 9200;
let substr = t.toString().substr(0, 8);
if(!result[substr])
result[substr] = 0;
result[substr] += element.count;
});
let returnResult = [];
result.forEach((element, index) =>
returnResult.push({
time: index,
count: element
})
);
return returnResult;
}

(javascript) local storage value -> Can I change the order of the objects? [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
I set the data to a key called 'todo' in Local Storage.
The structure is like this.
key: todo
value : [{"text":"text1","idx":1, "complete":"Y"},
{"text":"text2","idx":2, "complete":"N"},
{"text":"text4","idx":4, "complete":"Y"}]
My to-do list can be deleted and changed between 'complete' and 'incomplete' status.
I want to change the order of to-do to the bottom when it is completed.
For example,
{"text": "text1", "idx": 1, "complete": "Y"}
When the "complete" value of this object has changed to "N".
({"text": "text1", "idx": 1, "complete": "N"})
I want this result.
key: todo
value : [{"text":"text4","idx":4, "complete":"Y"},
{"text":"text2","idx":2, "complete":"N"},
{"text":"text1","idx":1, "complete":"N"}]
The completed to-do wants to appear at the bottom.
Use custom sort function Array.prototype.sort(function(){})
let tasks = {
key: "todo",
value: [{
"text": "text1",
"idx": 1,
"complete": "Y"
},
{
"text": "text2",
"idx": 2,
"complete": "N"
},
{
"text": "text4",
"idx": 4,
"complete": "Y"
}
]
};
tasks.value.sort((a1, a2) => {
if (a1.complete == "Y") {
if (a2.complete == "Y")
return 0;
else
return -1;
} else {
if (a2.complete == "Y")
return 1;
else
return 0;
}
})
console.log(tasks);

Counting object in side array of array object by property 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 3 years ago.
Improve this question
I have data like:
var data = [
{
items: [
{
id: 123
},
{
id: 234
},
{
id: 123
}
]
}, {
items: [
{
id: 123
},
{
id: 234
}
]
}
]
so, I want count object deep in array inside of all data by property 'id'.
ex: data.countObject('id',123) //return 3.
and my data have about xx.000 item, which solution best?
Thanks for help (sorry for my English)
You can use reduce & forEach. Inside the reduce callback you can access the items array using curr.items where acc & curr are just parameters of the call back function. Then you can use curr.items.forEach to get each object inside items array
var data = [{
items: [{
id: 123
},
{
id: 234
},
{
id: 123
}
]
}, {
items: [{
id: 123
},
{
id: 234
}
]
}];
function getCount(id) {
return data.reduce(function(acc, curr) {
// iterate through item array and check if the id is same as
// required id. If same then add 1 to the accumulator
curr.items.forEach(function(item) {
item.id === id ? acc += 1 : acc += 0;
})
return acc;
}, 0) // 0 is the accumulator, initial value is 0
}
console.log(getCount(123))

Categories