Looping inside an array of object - javascript

I need some help with my code here. It's a jquery-bracket project.
I have an object that has an array inside, there's a line of array i want to loop so I don't have to manually generated those lines
var team = ["Team 1", "Team 2", "Team 3", "Team 4"];
var result = [1, 2, 2, 1];
var teams = "";
for (i = 0; i < team.length; i++) {
teams += [`["${team[i++]}"`, ` "${team[i]}"], \n`]
}
var singleElimination = {
"teams": [
// line that I needed for loop
[team[0], team[1]],
[team[2], team[3]],
],
"results": [
[
[
// also line that I needed for loop
[result[0], result[1]]
]
]
]
}
I have tried to pass the loop into a variable and passing them inside of an array, but it doesn't seems work.
sorry for my bad English, looking forward for the answer!
demo : https://quizzical-stonebraker-2d808a.netlify.com/

You can simply use team.join(',');
eg:-
var singleElimination = {
"teams": [
[team.join(',')]

var team = ["Team 1", "Team 2", "Team 3", "Team 4"];
var result = [1, 2, 2, 1];
var obj = {}
for(var i=0; i<team.length; i++){
obj[team[i]] = result[i];
}
console.log(obj)

var team = ["Team 1", "Team 2", "Team 3", "Team 4"];
var result = [1, 2, 2, 1];
var singleElimination = {
teams: [
// line that I needed for loop
[team[0], team[1]],
[team[2], team[3]]
],
results: [
[
[
// also line that I needed for loop
[result[0], result[1]],
[result[2], result[3]]
]
]
]
};
console.log("singleElimination", singleElimination);
var _teams = "";
singleElimination.teams.forEach(element => {
element.forEach((team, index) => {
_teams += element[index] + ", ";
});
});
var _teamResults = "";
singleElimination.results.forEach(element => {
element.forEach((team, index) => {
_teamResults += element[index] + ", ";
});
});
console.log("_teams", _teams);
console.log("_teamResults", _teamResults);

Related

Looking to filter array and make them into 2 arrays based on a flag if true or false

I am planning to filter an array into 2 separate arrays based on flag in one of the inner arrays but having trouble. Please help me with my code.
How do we get 2 separate arrays out of apiData to have objects filtered in types array based on flag value
var apiData = [{
"id": 1,
"types": [{
"id": "1.1",
"flag": true,
},
"id": "1.2",
"flag": false
}]
},
"id": 2,
"types": [{
"id": "2.1",
"flag": true,
}]
}
]
My Result should be like this for filteredTrueArray [{
"id": 1,
"types": [{
"id": "1.1",
"flag": true,
}]
},
"id": 2,
"types": [{
"id": "2.1",
"flag": true,
}]
}
]
I wanted $scope.filteredTrueArray to have types array with flag=true value objects and another array to have types array with only flag=false objects. Below is my code
$scope.filteredTrueArray = apiData.filter(function(item) {
var isTrueFound = item.types.some(function (el) {
return el.flag == true;
});
if(isTrueFound){
for(var i=0;i<item.types.length>0;i++)
{
if(item.types[i].flag == true){
$scope.filteredTrueArray.push(item.types[i]);
}
}
}
});
I've written a simple filter function. Please take a look!
var apiData = [{
"id": 1,
"types": [{
"id": "1.1",
"flag": true,
}, {
"id": "1.2",
"flag": false
}]
}, {
"id": 2,
"types": [{
"id": "2.1",
"flag": true,
}]
}];
function filterByTypeFlag(records, flagValue) {
var filtered = [];
records.forEach(function (record) {
var matchedTypes = [];
record.types.forEach(function (type) {
if (type.flag === flagValue) {
matchedTypes.push(type);
}
});
if (matchedTypes.length) {
filtered.push({
"id": record.id,
"types": matchedTypes
});
}
});
return filtered;
}
filterByTypeFlag(apiData, true);
filterByTypeFlag(apiData, false);
Here is a sample code that creates an object with a boolean value and creates 2 arrays of objects bases off their boolean value. Sorry if I misunderstood what you were looking for.
var objArray = [];
class testObj {
constructor(Oname, test1) {
this.name = Oname;
this.isABoolean = test1;
objArray.push(this);
}
}
var test1 = new testObj("test1", false);
var test2 = new testObj("test2", true);
var test3 = new testObj("test3", false);
var test4 = new testObj("test4", true);
var test5 = new testObj("test5", false);
var objArray = [test1, test2, test3, test4, test5];
var trueArray = [];
var falseArray = [];
function createArrays() {
for (var i = 0; i < objArray.length; i++) {
if (objArray[i].isABoolean === true) {
trueArray.push(objArray[i]);
//console.log(trueArray[i].name);
} else if (objArray[i].isABoolean === false) {
falseArray.push(objArray[i]);
}
}
}
createArrays();
for (var j = 0; j < trueArray.length; j++) {
console.log("True value: " + trueArray[j].name);
}
for (var k = 0; k < falseArray.length; k++) {
console.log("False value " + falseArray[k].name);
}
EDIT: I cleaned it up to automatically add the objects to an array upon creation.
One solution is to use map() with a filter() for get the new types array.
var apiData = [
{
"id": 1,
"types": [
{"id": "1.1", "flag": true},
{"id": "1.2", "flag": false}
]
},
{
"id": 2,
"types": [
{"id": "2.1", "flag": true}
]
}
];
let filteredTrueArray = apiData.map(
({id, types}) => ({id, types: types.filter(x => x.flag)})
)
.filter(({types}) => types.length);
let filteredFalseArray = apiData.map(
({id, types}) => ({id, types: types.filter(x => !x.flag)})
)
.filter(({types}) => types.length);
console.log("FilteredTrueArray:", filteredTrueArray);
console.log("FilteredFalseArray:", filteredFalseArray);

Javascript merge 2 arrays into a 3rd array to get all data required

I have 2 separate arrays which I need to merge into a third one so I can get all the data required.
Basically the 1st array has an id, and name and in order to get the address I need to search inside the 2nd array and match the id's so I can have all the data from the person.
Here is the data and code:
//Array 1
var myPeopleArray = [{"people":[{"id":"123","name":"name 1"},{"id":"456","name":"name 2"}]}];
//Array 2
var myPersonArray = [{"person":[{"id":"123","address":"address 1"},{"id":"456","address":"address 2"}]}];
var arrayLength = myPeopleArray[0].people.length;
for (var i = 0; i < arrayLength; i++) {
console.log("id: " + myPeopleArray[0].people[i].id);
}
//Wanted Result:
[{"people":[
{
"id":"123",
"name":"name 1",
"address":"address 1"
},
{
"id":"456",
"name":"name 2",
"address":"address 2"
}
]
}]
How can I do this?
var myPeopleArray = [{"people":[{"id":"123","name":"name 1"}, {"id":"456","name":"name 2"}]}];
var myPersonArray = [{"person":[{"id":"123","address":"address 1"}, {"id":"456","address":"address 2"}]}];
for(var i=0;i<myPeopleArray[0].people.length;i++)
{
myPeopleArray[0].people[i].address = myPersonArray[0].person[i].address;
}
document.write(JSON.stringify(myPeopleArray));
You could iterate both arrays and build new object with the joined properties.
var myPeopleArray = [{ "people": [{ "id": "123", "name": "name 1" }, { "id": "456", "name": "name 2" }] }],
myPersonArray = [{ "person": [{ "id": "123", "address": "address 1" }, { "id": "456", "address": "address 2" }] }],
hash = Object.create(null),
joined = [],
joinById = function (o) {
if (!(o.id in hash)) {
hash[o.id] = {};
joined.push(hash[o.id]);
}
Object.keys(o).forEach(function (k) {
hash[o.id][k] = o[k];
});
};
myPeopleArray[0].people.forEach(joinById);
myPersonArray[0].person.forEach(joinById);
console.log(joined);

lodash: count values from array of objects

I have an array of objects like this:
[
{"question":"Q1","answer":"my answer 2"},
{"question":"Q1","answer":"my answer"}
{"question":"Q1","answer":"my answer"}
{"question":"Q2","answer":"answer 2"}
]
I would like to group by the question keys and return the counts of each answer.
e.g.
{
"Q1": [{
"answer": "my answer",
"count": 2
}, {
"answer": "my answer 2",
"count": 1
}],
"Q2": [{
"answer": "answer 2",
"count": 1
}]
}
,
I am able to groupBy questions using:
.groupBy("question") and count occurances of values using .countBy() but I am not sure how to combine the grouping and counting functions to achieve the desired output?
You can start with _.groupBy(array, 'question') - then use .map
For example:
var arr = [
{"question":"Q1","answer":"my answer 2"},
{"question":"Q1","answer":"my answer"},
{"question":"Q1","answer":"my answer"},
{"question":"Q2","answer":"answer 2"}
];
var result = _(arr)
.groupBy('question')
.map(function(item, itemId) {
var obj = {};
obj[itemId] = _.countBy(item, 'answer')
return obj
}).value();
console.log(JSON.stringify(result, null, 2));
See the working version at: http://jsbin.com/wixoronoqi/edit?js,console
Here is a native/vanilla js solution to this problem, using Array.reduce(), with and without the spread operator.
With spread operator, immutable style :
const questions = [
{"question":"Q1","answer":"my answer 2"},
{"question":"Q1","answer":"my answer"},
{"question":"Q1","answer":"my answer"},
{"question":"Q2","answer":"answer 2"}
];
const groupedQuestions = questions.reduce( (g, q) => {
return {
...g,
[q.question]: {
...g[q.question],
[q.answer] : (g[q.question] && g[q.question][q.answer] || 0) + 1
}
}
}, {})
document.write(JSON.stringify(groupedQuestions))
Without spread operator :
const questions = [
{"question":"Q1","answer":"my answer 2"},
{"question":"Q1","answer":"my answer"},
{"question":"Q1","answer":"my answer"},
{"question":"Q2","answer":"answer 2"}
];
const groupedQuestions = questions.reduce( (g, q) => {
typeof g[q.question] !== "undefined" || (g[q.question] = {});
typeof g[q.question][q.answer] !== "undefined" || (g[q.question][q.answer] = 0);
g[q.question][q.answer] += 1;
return g;
}, {})
document.write(JSON.stringify(groupedQuestions))
A "native javascript" solution using Array.forEach and Array.push functions:
var arr = [{"question":"Q1","answer":"my answer 2"},{"question":"Q1","answer":"my answer"}, {"question":"Q1","answer":"my answer"}, {"question":"Q2","answer":"answer 2"}];
var result = {};
arr.forEach(function(v){
var key = v['question'], Q = this[key], found = false;
if (Q) {
var len = Q.length;
while (len--) {
if (Q[len]['answer'] === v['answer']) {
Q[len]['count']++;
found = true;
}
}
if (!found) Q.push({'answer': v['answer'], 'count' : 1});
} else {
this[key] = [];
this[key].push({'answer': v['answer'], 'count' : 1});
}
}, result);
console.log(JSON.stringify(result, 0, 4));
The output:
{
"Q1": [
{
"answer": "my answer 2",
"count": 1
},
{
"answer": "my answer",
"count": 2
}
],
"Q2": [
{
"answer": "answer 2",
"count": 1
}
]
}

javascript d3 get the biggest value from a multi-nested array/object dataset

how would I reduce bunch of deeply nested arrays and get the biggest value for certain keys?
here is my data format:
var data = [
{
"category": "Cat 1",
"subcategories": [
{
"subcategory": "Subcate 1 a",
"problems": [
{
"problem": "Problem 1 a 1",
"total": 3,
"breakdown": {
"moderate": 1,
"severe": 2
}
},
{
"problem": "Problem 1 a 2",
"total": 6,
"breakdown": {
"moderate": 5,
"severe": 1
}
}
]
}
]
},
{
"category": "Cat 2",
"subcategories": [
{
"subcategory": "Subcate 2 a",
"problems": [
{
"problem": "Problem 2 a 1",
"total": 8,
"breakdown": {
"moderate": 5,
"severe": 3
}
}
]
},
{
"subcategory": "Subcat 2 b",
"problems": [
{
"problem": "Problem 2 b 1",
"total": 4,
"breakdown": {
"moderate": 1,
"severe": 3
}
},
{
"problem": "Problem 2 b 2",
"total": 2,
"breakdown": {
"moderate": 2,
"severe": 0
}
}
]
}
]
}
]
How would I get an array of every value for "moderate" and "severe"? So in this example I would need
[1,2,5,1,5,3,1,3,2,0]
And then I would like to do d3.max(array) to get the biggest value from it.
This is the working fiddle .Just convert the object into array like this:
var array = $.map(data, function(value, index) {
return [value];
});
var arr =[];
for(var key in array)
{
var subcategories = array[key]['subcategories'];
for(var j in subcategories)
{
var prob = subcategories[j]['problems'];
for(var i in prob)
{
var moderate = prob[i]['breakdown']['moderate'];
var severe = prob[i]['breakdown']['severe'];
arr.push(moderate);
arr.push(severe);
}
}
}
alert(arr); //required array
var max = d3.max(arr) //required max value
and loop through it and save the values into a final array!
This is a little long-winded but it might work:
var array = new Array();
for (var h=0; h<data.length; h++){
for (var i=0; i<data[h].length; i++){
for (var j=0; j<data[h].subcategories[i].length; j++){
for (var k=0; k<data[h].subcategories[i].problems[j].length; k++){
array.push(data[h].subcategories[i].problems[j].breakdown.moderate);
array.push(data[h].subcategories[i].problems[j].breakdown.severe);
}
}
}
}
//Then get the max of array
I may have made a mistake somewhere, but you could use this general idea to produce the desired result.
In order to pass deeply nested json use jsonpath jQuery plugin
Fiddle
JS:
var mod=jsonPath(data, '$..subcategories..problems..moderate');
var path=mod.concat(jsonPath(data, '$..subcategories..problems..severe'));
$("#max").html(d3.max(path));

Sorting an array of objects with multiple entries

I would like to rearrange an array of objects in javascript, which looks like this:
[{ year: "1950-12-20", product: ["product 1", "product 2, "product 3"] }, { year: "1951-12-20", product: ["product 3", "product 2"] }, { year: "1952-12-20", product: ["product 3", "product 4"] }]
so that I get two arrays, one with the products and one with the years when they appear.
a = ["product 1", "product 2", "product 3", "product 4"]
b = ["1950-12-20", [ "1950-12-20, "1951-12-20"],["1950-12-20", "1951-12-20", "1952-12-20"],"1952-12-20"]
I have tried to loop through each object through nestled for-loops, but how do I treat the array of strings in the object array in a nice way?
I don't know what kind of loop you have tested, but this type of code is not so long for what has to be done :
var data = [{ year: "1950-12-20", product: ["product 1", "product 2", "product 3"] }, { year: "1951-12-20", product: ["product 3", "product 2"] }, { year: "1952-12-20", product: ["product 3", "product 4"] }];
var nbData = data.length, iData;
var years = [], products = [], dictProductsYear = {};
var nbProducts, iProduct, p;
// Loop through years
for(iData = 0; iData < nbData; iData ++) {
products = data[iData].product;
nbProducts = products.length;
// Add the current year to the concerned products
for(iProduct = 0; iProduct < nbProducts; iProduct ++) {
p = products[iProduct];
// Registered product
if(dictProductsYear[p]) dictProductsYear[p].push(data[iData].year);
// Unregistered one
else dictProductsYear[p] = [ data[iData].year ];
}
}
var yearList = [], productList = [];
// Flatten the dictionary in 2 lists
for(p in dictProductsYear) {
productList.push(p);
yearList.push(dictProductsYear[p]);
}
This looks a bit like #Samuel Caillerie's code, but is more concise:
var data = [{ year: "1950-12-20", product: ["product 1", "product 2", "product 3"] }, { year: "1951-12-20", product: ["product 3", "product 2"] }, { year: "1952-12-20", product: ["product 3", "product 4"] }];
var yearsByProd = {};
for (var i=0; i<data.length; i++) {
var prod = data[i].product;
for (var j=0; j<prod.length; j++) {
if (prod[j] in yearsByProd)
yearsByProd[prod[j]].push(data[i].year);
else
yearsByProd[prod[j]] = [data[i].year];
}
}
var a, b;
b = (a = Object.keys(yearsByProd).sort()).map(function(prod) {
// add an if-else-statement here if you want to extract single years from their array
return yearsByProd[prod];
});

Categories

Resources