Find every possibilitie in an array of object comparing key values - javascript

I have an specific math formula which receives three parameters and I'm trying to get from an array of object all the possibilities to run this math formula.
It's regards to sports.
Imagine a match where there are 3 possibility: Team A (win) - Team B (win) - Draw.
3 bet websites are dealing with this event. But the 3 of them have different odds values for this match.
I want to run those 3 bet websites to get all posibilities I can have for this event. Never getting more than one odd from the same bet website.
Example:
Website A: team A (win)
Website B: team B (win)
Website C: draw
I'm using JavaScript for that.
Thank you in advance for you time and support.
Really appreciate that.
Here is an example of data I have to get these possibilities.
Each obj is a website and into the object, the odds are on the key "outcomes".
The array of object here has 3 objects, but it can have more
[
{
"key": "betmgm",
"title": "BetMGM",
"last_update": "2022-12-14T04:30:40Z",
"markets": [
{
"key": "h2h",
"outcomes": [
{
"name": "AC Milan",
"price": 138
},
{
"name": "Tottenham Hotspur",
"price": 200
},
{
"name": "Draw",
"price": 225
}
]
}
]
},
{
"key": "barstool",
"title": "Barstool Sportsbook",
"last_update": "2022-12-14T04:30:22Z",
"markets": [
{
"key": "h2h",
"outcomes": [
{
"name": "AC Milan",
"price": 130
},
{
"name": "Tottenham Hotspur",
"price": 220
},
{
"name": "Draw",
"price": 230
}
]
}
]
},
{
"key": "twinspires",
"title": "TwinSpires",
"last_update": "2022-12-14T04:17:45Z",
"markets": [
{
"key": "h2h",
"outcomes": [
{
"name": "AC Milan",
"price": 130
},
{
"name": "Tottenham Hotspur",
"price": 220
},
{
"name": "Draw",
"price": 230
}
]
}
]
}
]
I would like to receive an array with the possibilities like this:
[
{
"bookMaker": "TwinSpires",
"name": "Tottenham Hotspur",
"price": 230,
},
{
"bookMaker": "Barstool Sportsbook",
"name": "AC Milan",
"price": 130,
},
{
"bookMaker": "BetMGM",
"name": "Draw",
"price": 225,
}
]

The algorithm is quite simple. First, we take all the outcomes of the first Bet website. We shuffle them randomly.
Then we simply loop through the JSON object, which is a list of bet websites, not to mention the fact that both the number of outcomes must be the same as the number of bet websites. We assign for each bet website the next item of the shuffled outcomes. We log it to the console.
Here is the algorithm:
var data = [
{
"key": "betmgm",
"title": "BetMGM",
"last_update": "2022-12-14T04:30:40Z",
"markets": [
{
"key": "h2h",
"outcomes": [
{
"name": "AC Milan",
"price": 138
},
{
"name": "Tottenham Hotspur",
"price": 200
},
{
"name": "Draw",
"price": 225
}
]
}
]
},
{
"key": "barstool",
"title": "Barstool Sportsbook",
"last_update": "2022-12-14T04:30:22Z",
"markets": [
{
"key": "h2h",
"outcomes": [
{
"name": "AC Milan",
"price": 130
},
{
"name": "Tottenham Hotspur",
"price": 220
},
{
"name": "Draw",
"price": 230
}
]
}
]
},
{
"key": "twinspires",
"title": "TwinSpires",
"last_update": "2022-12-14T04:17:45Z",
"markets": [
{
"key": "h2h",
"outcomes": [
{
"name": "AC Milan",
"price": 130
},
{
"name": "Tottenham Hotspur",
"price": 220
},
{
"name": "Draw",
"price": 230
}
]
}
]
}
];
start(data);
function start(data) {
var outcomes = data[0].markets[0].outcomes;
if (data.length != outcomes.length) {
alert("Invalid data!");
return;
}
var results = createResults(data);
printResults(results);
}
function createResults(data) {
var outcomes = data[0].markets[0].outcomes;
var newOutcomesNames = shuffleOutcomes(outcomes);
var results = [];
for (var i = 0; i < data.length; i++) {
var currentBetWebsite = data[i];
var currentResult = {};
var currentOutcomes = currentBetWebsite.markets[0].outcomes;
currentResult.bookMaker = currentBetWebsite.title;
currentResult.name = newOutcomesNames[i];
for (var j = 0; j < newOutcomesNames.length; j++) {
if (newOutcomesNames[i] == currentOutcomes[j].name) {
currentResult.price = currentOutcomes[j].price;
}
}
results.push(currentResult);
}
return results;
}
function printResults(results) {
console.log(results);
}
function shuffleOutcomes(outcomes) {
var parsedOutcomes = parseOutcomesNames(outcomes);
var outcomesLength = parsedOutcomes.length;
var newOutcomes = [];
for (var i = 0; i < outcomesLength; i++) {
var random = Math.floor(Math.random() * (outcomesLength - i));
newOutcomes.push(parsedOutcomes[random]);
parsedOutcomes.splice(random, 1);
}
return newOutcomes;
}
function parseOutcomesNames(outcomes) {
var outcomesNames = outcomes.map(o => o.name);
return outcomesNames;
}
Let me know, if you need any further assistance.

Related

how to transform a key property from an object type into an array type

I have a array of two objects.
I would like to transforming each object's key, allocation, from a object type into array type
From allocation: {} into allocation:[]
They content of the array of allocation would be the children of customAllocations
May I ask how to achieve that?
Original array
[
{
"allocation": {
"name": "custom",
"customAllocations": [
{
"name": "Developed",
"weight": 0.75
},
{
"name": "Diversified",
"weight": 0.1
},
{
"name": "Global",
"weight": 0.15
}
]
}
},
{
"allocation": {
"name": "custom",
"customAllocations": [
{
"name": "Developed",
"weight": 0.35
},
{
"name": "Conservative",
"weight": 0.1
},
{
"name": "Global",
"weight": 0.55
}
]
}
}
]
Expected array
[
{
"allocation": [
{
"name": "Developed",
"weight": 0.75
},
{
"name": "Diversified",
"weight": 0.1
},
{
"name": "Global",
"weight": 0.15
}
]
},
{
"allocation": [
{
"name": "Developed",
"weight": 0.35
},
{
"name": "Conservative",
"weight": 0.1
},
{
"name": "Global",
"weight": 0.55
}
]
}
]
Edit:
Please be aware of modifying the actual object. It may have some problem. So may I know how to have a better approach...That's why I found this problem may have more than it to be.
You can map the properties like so. However this will mutate the original obj. You can use for example use _.deepClone(data) from loadash to make a copy of the inital obj.
const data = [{
"allocation": {
"name": "custom",
"customAllocations": [{
"name": "Developed",
"weight": 0.75
},
{
"name": "Diversified",
"weight": 0.1
},
{
"name": "Global",
"weight": 0.15
}
]
}
},
{
"allocation": {
"name": "custom",
"customAllocations": [{
"name": "Developed",
"weight": 0.35
},
{
"name": "Conservative",
"weight": 0.1
},
{
"name": "Global",
"weight": 0.55
}
]
}
}
];
// this will mutate the actualy obj
console.log(data.map(alloc => {
alloc.allocation = alloc.allocation.customAllocations
return alloc
}))
// this will also display the changed result
console.log(data)
I guess it meets your needs. Just a little playing on the object and returning your expected data form.
const data = [
{
"allocation": {
"name": "custom",
"customAllocations": [
{
"name": "Developed",
"weight": 0.75
},
{
"name": "Diversified",
"weight": 0.1
},
{
"name": "Global",
"weight": 0.15
}
]
}
},
{
"allocation": {
"name": "custom",
"customAllocations": [
{
"name": "Developed",
"weight": 0.35
},
{
"name": "Conservative",
"weight": 0.1
},
{
"name": "Global",
"weight": 0.55
}
]
}
}
]
const newData = []
data.forEach(elem => {
newData.push({'allocation' : elem.allocation.customAllocations})
})
console.log(newData)

How to groupBy an attribute inside the second array with javascript

I am trying to convert an array object to a new set of arrays grouped by their value. In this case, it is the date value.
What I have tried in in the below code, but I didn't get the results of what I wanted. Can you please help me find the right solution for this problem?
INPUT
let array = [
{
"category": {
"code": "1558950145861"},
"lines": [
{
"date": "2020-02-26",
"price": 9260,
"dispo": 5
},
{
"date": "2020-02-29",
"price": 6300,
"dispo": 9
},
{
"date": "2020-04-01",
"price": 7700,
"dispo": 23
}
]
},
{
"category": {
"code": "1788858954441"
},
"lines": [
{
"date": "2020-02-26",
"price": 6260,
"dispo": 2
},
{
"date": "2020-02-29",
"price": 5500,
"dispo": 4
},
{
"date": "2020-04-01",
"price": 840,
"dispo": 7
}
]
}
];
Desired OUTPUT
[{
"date": "2020-02-26",
"lines": [{
"price": 9260,
"dispo": 5
}, {
"price": 6260,
"dispo": 2
}]
}, {
"date": "2020-02-29",
"lines": [{
"price": 6300,
"dispo": 9
}, {
"price": 5500,
"dispo": 4
}]
}, {
"date": "2020-04-01",
"lines": [{
"price": 7700,
"dispo": 23
}, {
"price": 840,
"dispo": 7
}]
}]
code that I wrote
var result = (_array)
.groupBy(x => {
for (let j = 0; j < x.lines.length; j += 1) {
return x.lines[j].date;
}
})
.map((value, key) => ({
date: key,
lines: value
})).value();
I want my code to generate the desired output, but it isn't doing that. What might I be doing wrong?
try this
let array = [{ "category": { "code": "1558950145861" }, "lines": [{ "date": "2020-02-26", "price": 9260, "dispo": 5 }, { "date": "2020-02-29", "price": 6300, "dispo": 9 }, { "date": "2020-04-01", "price": 7700, "dispo": 23 }] }, { "category": { "code": "1788858954441" }, "lines": [{ "date": "2020-02-26", "price": 6260, "dispo": 2 }, { "date": "2020-02-29", "price": 5500, "dispo": 4 }, { "date": "2020-04-01", "price": 840, "dispo": 7 }] }]
const groupBy = (arr) => arr.reduce((acc, ele)=>( (acc[ele.date] = acc[ele.date] || []).push(ele), acc),{})
const all = [].concat(...array.map(ele=> ele.lines))
const format = ele => ele.map(({price, dispo})=>({price, dispo}))
console.log(Object.entries(groupBy(all)).map(([date, lines])=> ({date, lines: format(lines)})))
Try something like this :
var out = {}
for (let i = 0; i < array.length; i++) {
for (let j = 0; j < array[i]["lines"].length; j++) {
let e = array[i]["lines"][j];
if (!out[e["date"]]) {
out[e["date"]] = [];
}
out[e["date"]].push({"price": e["price"], "dispo": e["dispo"]});
}
}
var result = [];
for (let k in out) {
result.push({"date": k, "lines": out[k]});
}
The result variable has the desired output format.
You don't appear to need the category value, so first I'd merge the lines into a single array where you can groupBy from there:
// using your input called 'array'
// First collect just the line arrays:
var arrayOfLineArrays=array.map(category => category.lines);
// Merge them into one bigger array:
var allLines = _.flatten(arrayOfLineArrays);
// Now you can groupBy with ease:
var dateGroupsObject = _(allLines).groupBy(line => line.date);
// And map to an array:
var result = _.values(_.mapObject(dateGroupsObject, (value, key) => ({
date: key,
lines: value
}))));

Find index of an element in javascript array of objects

I am new to javascript and want to find the index of the given key-value at the bottom but not able to do so. Where am i wrong? The data in the array is copied form a json file which is valid as checked on jsonlint.
var productArray=[
{
"name1":"Electronics",
"id1":{
"products1":{
"id":1.1,
"name":"Microsoft Keyboard",
"description":"good keyboard",
"rating":3,
"price":500,
"freeDeliv":true,
"seller":"MS",
"quanAvl":10
},
"products2":{
"id":1.2,
"name":"ASUS phone",
"description":"good phone",
"rating":4,
"price":10000,
"freeDeliv":true,
"seller":"ASUS",
"quanAvl":10
},
"products3":{
"id":1.3,
"name":"iPhone",
"description":"good phone",
"rating":3,
"price":50000,
"freeDeliv":false,
"seller":"Apple",
"quanAvl":100
}
},
"name2":"Clothing",
"id2":{
"products4":{
"id":2.1,
"name":"Jeans",
"description":"good Jeans",
"rating":3,
"price":800,
"freeDeliv":true,
"seller":"Levis",
"quanAvl":100
},
"products5":{
"id":2.2,
"name":"TShirt",
"description":"good TShirt",
"rating":4,
"price":1000,
"freeDeliv":true,
"seller":"Peter",
"quanAvl":1000
},
"products6":{
"id":2.3,
"name":"Sherwani",
"description":"very good",
"rating":4,
"price":50000,
"freeDeliv":false,
"seller":"Maanyavar",
"quanAvl":1000
}
}},
];
var display=function(productArray,prodKey,value){
for(x in productArray)
{
if(productArray[x][prodKey]==value)
{
console.log(x);
}
else{
alert("Not Found");
}
}
}
display(productArray,"name","Sherwani");
this is the answer. I have tried this
var display=function(productArray_,prodKey,value){
p = productArray_[0]["id2"];
found = false;
for (var key in p) {
if (p.hasOwnProperty(key)) {
p2 = p[key];
for(var key2 in p2){
if(p2.hasOwnProperty(key2)){
if(key2 == prodKey && p2[key2] == value){
console.log(key2); //index of value you looking for
console.log(p2[key2]) //value from index you looking for
alert(key2);
found = true;
}
}
}
}
}
if(!found)
alert("not found");
}
display(productArray,"name","Sherwani");
but I'm agree, this is a very bad object structure. you should change the json structure so you can parse it more easily
UPDATE: you should avoid creating json object wherever possible (begins with "{" and ends with "}"), and instead create json array (begins with "[" and ends with "]").
here is a better structure and how to parse it
var productArray=[
{
"name": "Electronics",
"list": [
{
"code": "products1",
"id": 1.1,
"name": "Microsoft Keyboard",
"description": "good keyboard",
"rating": 3,
"price": 500,
"freeDeliv": true,
"seller": "MS",
"quanAvl": 10
},
{
"code": "products2",
"id": 1.2,
"name": "ASUS phone",
"description": "good phone",
"rating": 4,
"price": 10000,
"freeDeliv": true,
"seller": "ASUS",
"quanAvl": 10
},
{
"code": "products3",
"id": 1.3,
"name": "iPhone",
"description": "good phone",
"rating": 3,
"price": 50000,
"freeDeliv": false,
"seller": "Apple",
"quanAvl": 100
}
]
},
{
"name": "Clothing",
"list": [
{
"code": "products4",
"id": 2.1,
"name": "Jeans",
"description": "good Jeans",
"rating": 3,
"price": 800,
"freeDeliv": true,
"seller": "Levis",
"quanAvl": 100
},
{
"code": "products5",
"id": 2.2,
"name": "TShirt",
"description": "good TShirt",
"rating": 4,
"price": 1000,
"freeDeliv": true,
"seller": "Peter",
"quanAvl": 1000
},
{
"code": "products6",
"id": 2.3,
"name": "Sherwani",
"description": "very good",
"rating": 4,
"price": 50000,
"freeDeliv": false,
"seller": "Maanyavar",
"quanAvl": 1000
}
]
},
]
var display=function(productArray_,prodKey,value){
found = false;
for(var key in productArray_){
for(var key2 in productArray_[key]){
if(key2 == "list"){
for(var key3 in productArray_[key][key2]){
for(var key4 in productArray_[key][key2][key3]){
if(key4 == prodKey
&& productArray_[key][key2][key3][key4] == value
){
console.log(key4);
console.log(productArray_[key][key2][key3][key4]);
alert(key4);
found = true;
}
}
}
}
}
}
if(!found)
alert("not found");
}
display(productArray,"name","Sherwani");
Name you are looking for in your example is one level deeper. This should work:
var display = function(productArray, prodKey, value){
for (x in productArray) {
for (prod in productArray[x]) {
if (productArray[x][prod][prodKey] == value) {
console.log(x);
} else {
alert("Not Found");
}
}
}
}

Filter JSON objects based on condition in Backbone

I have the below JSON response. In Backbone I want to filter some objects(names) from the array
For example - Here i need to loop only 'Jack','Mcd' objects(names. Need to get only Jack and Mcd names from arrary.
Can anyone give me any ideas to implement?
resultstest = {
"r": [{
"IsActive": false,
"re": {
"Name": "Depo"
},
"Expire": "Oct8, 2013",
"Clg": [{
"Name": "james",
"Rate": 0.05
}, {
"Name": "Jack",
"Rate": 0.55
}, {
"Name": "Ander",
"Rate": 0.46
}, {
"Name": "Mcd",
"Rate": 0.01,
}],
},
{
"IsActive": false,
"re": {
"Name": "Depo"
},
"Expire": "Oct8, 2013",
"Clg": [{
"Name": "james",
"Rate": 0.05
}, {
"Name": "Jack",
"Rate": 0.55
}, {
"Name": "Mcd",
"Rate": 0.01,
}],
},
{
"IsActive": false,
"re": {
"Name": "Depo"
},
"Expire": "Oct8, 2013",
"Clg": [{
"Name": "james",
"Rate": 0.05
}, {
"Name": "Jack",
"Rate": 0.55
}, {
"Name": "Mcd",
"Rate": 0.01,
}],
}]
};
loadjson = function (input) {
if (_.isArray(input)) {
var collection = new CompeCollection();
_.each(input, function (modelData) {
....
});
return collection;
}
};
var tablesResult = loadjson(resultstest.r[0].Clg); // can we filter here like resultstest.r[0].Clg(!="james" && !="Ander")
Is there any array method to filter those objects while passing to loadjson function? Any help would be helpful.
Thanks
You can use Array.filter method of arrays supported in modern browsers. For compatibility of old browsers, you can use _.filter (http://underscorejs.org/#filter).
So your code would be like,
var tablesResult = loadjson(_.filter(resultstest.r[0].Clg, function(clg) { return (clg.name !="james" && clg.name !="Ander"); }))
To DRY your code, you can event create this filter function separately and simple reference it here. Like,
var collegeFilter = function(clg) { return (clg.name !="james" && clg.name !="Ander"); }
...
var tablesResult = loadjson(_.filter(resultstest.r[0].Clg, collegeFilter));

take JSON input and store it in to an array (javascript)

I have a JSON input of
{
"Categories": {
"Facets": [{
"count": 1,
"entity": "Company",
"Company": [{
"entity": "Ford Motor Co",
"Ford_Motor_Co": [{
"count": 1,
"entity": "Ford"
}]
}]
}, {
"count": 4,
"entity": "Country",
"Country": [{
"entity": "Germany",
"Germany": [{
"count": 1,
"entity": "Germany"
}],
"currency": "Euro (EUR)"
}, {
"entity": "Italy",
"Italy": [{
"count": 1,
"entity": "Italy"
}],
"currency": "Euro (EUR)"
}, {
"entity": "Japan",
"Japan": [{
"count": 1,
"entity": "Japan"
}],
"currency": "Yen (JPY)"
}, {
"entity": "South Korea",
"South_Korea": [{
"count": 1,
"entity": "South Korea"
}],
"currency": "Won (KRW)"
}]
}, {
"count": 5,
"entity": "Persons",
"Persons": [{
"count": 2,
"entity": "Dodge"
}, {
"count": 1,
"entity": "Dodge Avenger"
}, {
"count": 1,
"entity": "Major League"
}, {
"count": 1,
"entity": "Sterling Heights"
}]
}]
}
}
I need to get the values for entity in each level in to an array..
[Company, Ford Motor Co, Ford, ....... , Sterling Heights]
I am able to get thru the first level with the code
for (var k in h.Categories.Facets)
{
alert(h.Categories.Facets[k].entity);
}
How do I reach thru the innerlevels to get the values of entity??
You should do a foreach on each entity. If you know how many levels there are you can nest loops. If not - probably should go for a recursive function.
Edit
Recursive function:
function getEntities(ent)
{
alert(ent);
for (var l in ent)
{
getEntities(ent[l].entity);
}
}
Then use:
for (var k in h.Categories.Facets)
{
getEntities(h.Categories.Facets[k]);
}
Good luck!
The most general recursive answer:
function getEntities(any) {
var entities = [];
if ('entity' in any​) {
entities.push(any.entity);
}
for (var prop in any) {
if (any[prop] instanceof Object && any.hasOwnProperty(prop)) {
entities.append(getEntities(any[prop]));
}
}
return entities;
}
console.log(getEntities(h));
The line:
if (any[prop] instanceof Object && any.hasOwnProperty(prop)) {
Keeps numbers/nulls from bombing and the any.hasOwnProperty(prop) makes up for frameworks that like to attach to the Object prototype.
One way is to write a recursive method that accepts an array and extracts the methods from it.
As suggested, you can use a recursive function to loop through every possible nested combo:
var allEntities = [];
function getEntities(obj)
{
if (obj != null)
{
var entityName = obj["entity"];
alert(entityName);
if (entityName != null)
{
allEntities.push(entityName);
var adjName = entityName.replace(/ /gi, "_");
var entities = obj[adjName];
if (entities != null)
{
for (var e in entities)
{
var innerEntities = getEntities(entities[e]);
for (var inner in innerEntities)
allEntities.push(innerEntities[inner]);
}
}
}
}
}
for (var k in h.Categories.Facets)
{
alert(h.Categories.Facets[k].entity);
getEntities(h.Categories.Facets[k]);
}
alert(allEntities.length);

Categories

Resources