Grouping objects of array for knockout binding - javascript

I have an objects array that has 27 length:
[object(array)]
....
....
Each item in this array is empty or consists of an objects of array which has properties as shown below. This could have several loops so it will have many objects.
function MainTests(testName, section, totalExpected, totalPasssed, totalDuration, loopExpected, loopPassed, loopDuration) {
var self = this;
self.sectionName = section;
self.testName = testName;
self.totalPassExpect = totalExpected;
self.totalPassRate = totalPasssed;
self.totalDuration = totalDuration;
self.loopPassExpected = loopExpected;
self.loopPassRate = loopPassed;
self.loopDuration = loopDuration;
}
I want to group by sectionName and testName like this:
{
section: sectionName,
tests: [testName:testName, totalPassExpect: totalExpected........loopDuration:loopDuration..]
}
I tried this but it only groups it by sectionName:
self.GroupMainTest = ko.computed(function () {
var mainTestArray = [];
for (var i = 0; i < allMainTests.length ; i++) {
var group = {};
var result = allMainTests[i];
if (result.length != 0) {
for (var j = 0; j < result.length; j++) {
if (group[result[j].sectionName] == undefined) {
group[result[j].sectionName] = [group[result[j].sectionName]];
}
group[result[j].sectionName].push(result[j].sectionName)
group[result[j].sectionName].push(result[j].totalPassExpect)
group[result[j].sectionName].push(result[j].totalPassRate)
group[result[j].sectionName].push(result[j].totalDuration)
group[result[j].sectionName].push(result[j].loopPassExpected)
group[result[j].sectionName].push(result[j].loopPassRate)
group[result[j].sectionName].push(result[j].loopDuration)
group[result[j].sectionName].push(result[j].testName)
}
mainTestArray.push(group);
}
else {
mainTestArray.push(result);
}
}
return mainTestArray;
});
My goal is to achieve similar to this plnkr.
Can you help?

Related

Having Trouble figuring out the highest value through a for in loop

I am having trouble figuring out a way to loop the object in the objectMap to give me the Highest value of the fruits it gathered.My question is, how do I get loop to get the highest value using a for in loop. I have attached my code below.And where i have stopped,by the for in loop
var fruitString = 'Banana,Banana,Pear,Orange,Apple,Melon,Grape,Apple,Banana,Grape,Melon,Grape,Melon,Apple,Grape,Banana,Orange,Melon,Orange,Banana,Banana,Orange,Pear,Grape,Orange,Orange,Apple,Apple,Banana'
var fruitList = fruitString.split(',')
var fruitMap = {};
function soldfruits(){
for (var i = 0; i < fruitList.length; i++) {
var currentFruit = fruitList[i]
if (fruitMap[currentFruit] === undefined) {// cehck if fruit is not available
fruitMap[currentFruit]= 0;
}
fruitMap[currentFruit] = fruitMap[currentFruit] +1
}
console.log(fruitMap);
}
soldfruits(fruitMap); // calling function for check.
for (var fruits in fruitMap) {
if ( ) {
}
}
Try this:
var fruitString = 'Banana,Banana,Pear,Orange,Apple,Melon,Grape,Apple,Banana,Grape,Melon,Grape,Melon,Apple,Grape,Banana,Orange,Melon,Orange,Banana,Banana,Orange,Pear,Grape,Orange,Orange,Apple,Apple,Banana'
var fruitList = fruitString.split(',')
var fruitMap = {};
function soldfruits(){
for (var i = 0; i < fruitList.length; i++) {
var currentFruit = fruitList[i]
if (fruitMap[currentFruit] === undefined) {
fruitMap[currentFruit]= 0;
}
fruitMap[currentFruit] = fruitMap[currentFruit] +1
}
console.log(fruitMap);
return fruitMap
}
var fmap = soldfruits(fruitMap);
var high = 0
var high_name = ''
for(var x in fmap)
{
if(fmap[x] > high)
{
high = fmap[x]
high_name = x
}
}
console.log(high + ' ' + high_name)
This code will return the highest number of fruit sold and also the names of those fruit.
var mostSold = 0;
var mostFruits = [];
for (var fruits in fruitMap) {
if (fruitMap[fruits] > mostSold) {
// store the number of fruit sold
mostSold = fruitMap[fruits];
// initialise the list with the fruit name
mostFruits = [fruits];
}
else if (fruitMap[fruits] == mostSold) {
// add the fruit name to the list
mostFruits.push(fruits);
}
}
console.log( mostSold + ' : ' + mostFruits );
Like this:
var highest = {fruit:"", num:0}
for (var fruit in fruitMap) {
var num = fruitMap[fruit];
if (num > highest.num) { // if the current number of fruits is greater than the saved
highest.fruit=fruit; // save the fruit
highest.num=num; // save the number
}
}
console.log(highest);
Alternatively sort the array using object sort and pop the last
var fruitString = 'Banana,Banana,Pear,Orange,Apple,Melon,Grape,Apple,Banana,Grape,Melon,Grape,Melon,Apple,Grape,Banana,Orange,Melon,Orange,Banana,Banana,Orange,Pear,Grape,Orange,Orange,Apple,Apple,Banana'
var fruitList = fruitString.split(',')
var fruitMap = {};
function soldfruits() {
for (var i = 0; i < fruitList.length; i++) {
var currentFruit = fruitList[i]
if (fruitMap[currentFruit] === undefined) {
fruitMap[currentFruit] = 0;
}
fruitMap[currentFruit] = fruitMap[currentFruit] + 1
}
console.log(fruitMap);
}
soldfruits(fruitMap);
var highest = {fruit:"", num:0}
for (var fruit in fruitMap) {
var num = fruitMap[fruit];
if (num > highest.num) {
highest.fruit=fruit;
highest.num=num;
}
}
console.log(highest);
You could loop with Array#forEach and check, if fruitList has a value of the propery fruit. If not take zero otherwise the value of the propery and add one. Then assign to the property.
var fruitString = 'Banana,Banana,Pear,Orange,Apple,Melon,Grape,Apple,Banana,Grape,Melon,Grape,Melon,Apple,Grape,Banana,Orange,Melon,Orange,Banana,Banana,Orange,Pear,Grape,Orange,Orange,Apple,Apple,Banana',
fruitList = fruitString.split(','),
fruitMap = {},
highest = 0;
fruitList.forEach(function (fruit) {
fruitMap[fruit] = (fruitMap[fruit] || 0) + 1;
if (fruitMap[fruit] > highest) {
highest = fruitMap[fruit];
}
});
console.log(fruitMap);
console.log(highest);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Push to an array in a nested loop is repeating the last value

I am trying to push elements to an array in a nested loop, but only the last item is getting repeated in the final array, where am I going wrong, very new to javascript asynchronous concept.Below is the function in which I push the items to an array.
$scope.showBeList = function(feed) {
if (feed[srcServ.KEY_CONTENT_TEXT]) {
var content = JSON.parse(feed[srcServ.KEY_CONTENT_TEXT])
if (content) {
$scope.beList = {};
for (var key in content) {
var decorationVal;
//reading value from a lokijs collection
var decoration = dataServ[srcServ.CONST_COLLECTION_DECORATION].find({
'name': key
});
if (decoration && decoration.length) {
decorationVal = decoration[0];
if (decorationVal != null) {
var tempObj = JSON.parse(decorationVal.value);
if (tempObj) {
var header = tempObj[key][key + '_HEADER'];
if (header) {
var counter = content[key].length;
var tempItems = [];
for (var j = 0; j < content[key].length; j++) {
(function(j) {
var obj = {};
obj[srcServ.KEY_MAIN_HEADER] = tempObj[key][srcServ.KEY_DESC];
obj[srcServ.KEY_SUB_HEADER] = header[srcServ.KEY_DESC];
obj.id = j;
var itemVal = content[key][j][key + '_HEADER'];
var details = [];
var notes = [];
for (var item in itemVal) {
var val = null;
var found = false;
for (var i = 0; i < header.field.length; i++) {
if (header.field[i].name == item) {
val = header.field[i];
found = true;
break;
}
}
if (found && val != null) {
val[srcServ.KEY_DESC_VALUE] = itemVal[item];
details.push(val);
}
}
obj.details = details;
counter--;
if (counter == 0) {
$scope.showMoreDetails = true;
$scope.beList.beItems = tempItems;
console.log(JSON.stringify($scope.beList));
}
tempItems.push(obj)
})(j);
// $scope.beList.beItems.push(obj);
}
}
}
}
}
}
}
}
}

Deleting from an array doesn't work

So, I'm trying to delete from an array if it's element value isn't equal to a value that I specified:
Code: http://pastebin.com/hUc3mVLv
$scope.enablePVR = function()
{
for (i = 0; i < $scope.new_epg.length; i++) {
start_time = convert_time($scope.new_epg[i].start);
$scope.new_epg[i].title = $scope.new_epg[i].title.replace(/<(?:.|\n)*?>/gm, '');
$scope.new_epg[i].description = "";
$scope.new_epg[i].time = start_time;
}
archiveEPG = [];
for(var i=0; i<archiveEPG.length; i++) {
var e = document.getElementById("dateSelect");
if($scope.new_epg[i].start.split(" ")[0] == e[e.selectedIndex].value) {
archiveEPG[archiveEPG.length+1] = $scope.new_epg[i];
}
}
document.getElementById("dateSelect").remove(0);
$scope.get_epg(null, true, archiveEPG);
}
.remove(0) isn't valid you can add this function to make it valid tho :
Array.prototype.remove = function(index) {
return this.splice(index, 1); // The second parameter is the number of elements to remove.
}

Javascript- how do you convert this foreach loop to a regular for-loop?

This nested loop is running really slow in my app so I'm trying to change it to use regular for-loops instead of foreach. I'm a little confused on the find() part. Can someone help me convert this nested loop so that it doesn't use any foreach loops? thanks.
var filters = [];
if (selectionTagFilters.length > 0) {
for (var i = 0; i < selectionTagFilters.length; i++) {
filterTree.forEach(function find(tag) {
if (tag.tagCategoryId == selectionTagFilters[i].tag.tagCategoryId) {
tag.tags.forEach(function find(tag) {
if (tag.tagId == selectionTagFilters[i].tag.tagId) {
filters.push({ tagHeader: tag.tagHeader, tagId: tag.tagId, tagCategoryId: tag.tagCategoryId });
}
});
}
});
}
}
var filters = [],
selectionTagFilterItem = null,
filterTreeItem = null,
tagItem = null;
for(var i = 0, ii = selectionTagFilters.length; i < ii; i++) {
selectionTagFilterItem = selectionTagFilters[i];
for(var fti, ftii = filterTree.length; fti < ftii; fti++) {
filterTreeItem = filterTree[fti];
if (filterTreeItem.tagCategoryId != selectionTagFilterItem.tag.tagCategoryId) continue;
for(var ti = 0, tii = filterTreeItem.tags.length; ti < tii; ti++) {
tagItem = filterTreeItem.tags[ti];
if (tagItem.tagId != selectionTagFilterItem.tag.tagId) continue;
filters.push({ tagHeader: tagItem.tagHeader, tagId: tagItem.tagId, tagCategoryId: tagItem.tagCategoryId });
}
}
}

Array doesn't get filled correctly

I have these JavaScript entities: Item and Items.
var exports = {};
exports.Item = function(item) {
if (item) {
for (var attr in this.attributes) {
var value = item[attr];
if (value !== undefined) {
this.attributes[attr] = value;
}
}
}
return this;
};
exports.Item.prototype.attributes = {
_id: "",
title: ""
};
exports.Items = function(items) {
if (items && items.length > 0) {
for (var i = 0; i < items.length; i++) {
this.add(items[i]);
}
}
};
exports.Items.prototype.arr = [];
exports.Items.prototype.add = function(item) {
if (item) {
item = new exports.Item(item);
this.arr.push(item.attributes);
}
};
exports.Items.prototype.toJSON = function() {
var json = [];
for (var i = 0; i < this.arr.length; i++) {
json.push(this.arr[i]);
}
return json;
};
var i1 = new exports.Item({
_id: "1",
title: "1"
});
var i2 = new exports.Item({
_id: "2",
title: "2"
});
var i3 = new exports.Item({
_id: "3",
title: "3"
});
var items = new exports.Items([i1,i2,i3]);
console.log(items.toJSON());
There is a problem which I cannot find. When I execute the following code I get the last item 3 times instead of all the items.
I am sure the mistake is something small I cannot see. Maybe you can help me?
Member variables shouldn't be initialized in the prototype. Prototype variables will be shared across all instances. Instead, define the members in the constructor. So, instead of this:
exports.Items.prototype.arr = [];
Do this:
exports.Items = function(items) {
    this.arr = []; // instance variable
if (items && items.length > 0) {
for (var i = 0; i < items.length; i++) {
this.add(items[i]);
}
}
};

Categories