Compare two arrays in angular and loop over them - javascript

I would like to combine two arrays on the same page to look up the right average rating for each cd, the cd list is in an ng-repeat and they can be matched both with the id_cd. How can i get the right average rating for each cd in the ng-repeat of the cd-listing?
I have the following codes in the landingpage.js
app.controller('LandingPageController',
function LandingPageController($scope, $http) {
function GetAllCdRating() {
$http({
method: 'Get',
url: "/LandingPage/GetAllCdRating"
})
.success(function (data) {
$scope.AllCdRating= data;
// the added section of Saurabh Agrawal
$scope.getValue = function(cd){
for (var i = 0; i < $scope.AllCdRating.length; i++) {
if ($scope.AllCdRating[i].id_cd == cd.id_cd) {
return $scope.AllCdRating[i].averageRating;
}
}
}
})
}
GetAllCdRating();
// looks like this and holds about 200 records for now
[
{
"id": 1,
"averageRating": 7,
"id_cd": 13586
},
{
"id": 2,
"averageRating": 8,
"id_cd": 13540
},
{
"id": 3,
"averageRating": 9,
"id_cd": 13547
},
{
"id": 4,
"averageRating": 6,
"id_cd": 13549
}
]
$scope.GetLastAddedCds = function () {
$http({
method: 'Get',
url: "/LandingPage/GetLastAddedcds"
})
.success(function (data) {
$scope.lastcds = data;
})
}
$scope.GetLastAddedCds ();
// looks like this and holds about 5000+ records
[
{
"id_cd": 13586,
"cdName": "the greatest hits",
},
{
"id_cd": 13606,
"cdName": "live or die",
}
]
}
so far for the body section:
<div ng-controller="LandingPageController">
<div class="srollcell" ng-repeat="cd in lastcds">
<div>{{cd.title}}</div>
<div>
{{getValue(cd)}}
</div>
</div>
</div>
So i added your section Saurabh Agrawal (thanks) but somehow it seems it doesn't count up [i] it stays on '0'

Here is the working example of what you are looking for
Try this
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script type="text/javascript">
var myapp = angular.module('myapp', []);
myapp.controller('FirstCtrl', function($scope) {
$scope.myArray = [
{
"id": 1,
"averageRating": 7,
"id_cd": 13586
},
{
"id": 2,
"averageRating": 8,
"id_cd": 13540
},
{
"id": 3,
"averageRating": 9,
"id_cd": 13547
},
{
"id": 4,
"averageRating": 6,
"id_cd": 13549
}];
$scope.myValues= [
{
"id_cd": 13586,
"cdName": "the greatest hits",
},
{
"id_cd": 13606,
"cdName": "live or die",
}];
$scope.getValue = function(val){
for (var i = 0; i < $scope.myArray.length; i++) {
if ($scope.myArray[i].id_cd == val.id_cd) {
return $scope.myArray[i].averageRating;
}
}
}
});
</script>
</head>
<body>
<div ng-app="myapp" ng-controller="FirstCtrl">
<div ng-repeat="val in myValues track by $index">
{{getValue(val)}}
</div>
</div>
</body>
</html>

Related

How to return object based on value in nested array? (Javascript)

I am trying to return all objects that have a specific 'id' in the nested array. In the sample data, I'd like to return all person objects with hobbies id of 2 (hiking).
The other question addresses the problem of finding all values in an array based on an object value.
This question differs from the previous because I need to return all objects based on a value inside of a nested array.
[
{
"id":111222,
"name":"Faye",
"age":27,
"hobbies":[
{
"id":2,
"name":"hiking"
},
{
"id":3,
"name":"eating"
}
]
},
{
"id":223456789001,
"name":"Bobby",
"age":35,
"hobbies":[
{
"id":2,
"name":"hiking"
},
{
"id":4,
"name":"online gaming"
}
]
}
]
function hasHobby(person, hobbyId) {
return person.hobbies.some(function(hobby) {
return hobby.id === hobbyId;
});
}
function filterByHobby(people, hobbyId) {
return people.filter(function(person) {
return hasHobby(person, hobbyId);
});
}
If you wanna use the new cool ES6 syntax:
function filterByHobby(people, hobbyId) {
return people.filter(
person => person.hobbies.some(
hobby => hobby.id === hobbyId
)
);
}
var arr = [
{
"id":111222,
"name":"Faye",
"age":27,
"hobbies":[
{
"id":2,
"name":"hiking"
},
{
"id":3,
"name":"eating"
}
]
},
{
"id":223456789001,
"name":"Bobby",
"age":35,
"hobbies":[
{
"id":2,
"name":"hiking"
},
{
"id":4,
"name":"online gaming"
}
]
}
];
arr.filter(function(obj) {
var hobbies = obj.hobbies;
var x = hobbies.filter(function(hob) {
if (hob.id == "2") return true;
});
if (x.length > 0) return true;
});
Try this, I think its solve your proble:
var arr = [{
"id": 111222,
"name": "Faye",
"age": 27,
"hobbies": [{
"id": 2,
"name": "hiking"
}, {
"id": 3,
"name": "eating"
}]
}, {
"id": 223456789001,
"name": "Bobby",
"age": 35,
"hobbies": [{
"id": 2,
"name": "hiking"
}, {
"id": 4,
"name": "online gaming"
}]
}];
var x = arr.filter(function(el) {
var rnel = el.hobbies.filter(function(nel) {
return nel.id == 2;
});
return rnel.length > 0 ? true :false;
});
alert(x.length);

loop and put array within array according to id failed

http://jsfiddle.net/rw0z9e2j/
var sports = [{
"id": 1,
"name": "baseball"
}, {
"id": 2,
"name": "Football"
}];
var playersData = [{
"sport_id": 2,
"id": "nv12",
"name": "James"
}, {
"sport_id": 2,
"id": "nv11",
"name": "Jean"
}];
var arr = [],
tempObj = {};
$.each(sports, function (i, obj) {
var sport_id = obj.id;
$.each(playersData, function (i, obj) {
if (sport_id == obj.sport_id) {
tempObj = {
"sport_id": obj.sport_id,
"id": obj.id,
"name": obj.name
};
arr.push(tempObj);
}
});
obj.players = arr;
});
console.log(sports);
I try to build an array of players and put them within sports group according to sport_id but above logic has failed. It didn't group properly, the player who's in sport_id = 1 should go to sport which its id = 1 but why it didn't?
what's wrong with above loop there?
I suppose this is what you want:
var sports = [{
"id": 1,
"name": "baseball"
}, {
"id": 2,
"name": "Football"
}];
var playersData = [{
"sport_id": 2,
"id": "nv12",
"name": "James"
}, {
"sport_id": 2,
"id": "nv11",
"name": "Jean"
}];
sports.forEach(function (a) {
var arr = [];
playersData.forEach(function (b) {
if (a.id == b.sport_id) {
arr.push(b);
}
});
a.players = arr;
});
document.write('<pre>' + JSON.stringify(sports, 0, 4) + '</pre>');
You're declaring your temp vars outside of your loops, these should be scoped to your loops and thrown away after each operation.
var arr = [],
tempObj = {};
http://jsfiddle.net/samternent/rw0z9e2j/2/
You have to put it after push:
arr.push(tempObj);
obj.players = arr;
Actually you need this:
var sports = [{
"id": 1,
"name": "baseball"
}, {
"id": 2,
"name": "Football"
}];
var playersData = [{
"sport_id": 2,
"id": "nv12",
"name": "James"
}, {
"sport_id": 2,
"id": "nv11",
"name": "Jean"
}];
var arr = [];
$.each(sports, function (i, obj) {
$.each(playersData, function (i, player) {
if (obj.id === player.sport_id) {
var tempObj = {
"sport_id": player.sport_id,
"id": player.id,
"name": player.name
};
arr.push(tempObj);
obj.players = arr;
}
});
});
console.log(sports);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Hope you want to put inside the Sports group, but you are adding inside the player array, please notice, so please call
obj.sports = arr;
Hope it solve your problem .

node tree from json data using angularjs using recursive function

I want to create a node tree from a json.
index.html should load node tree recursively from person.json
and now the method is going into infinite loop.
please help me.
app.js
(function() {
var app = angular.module("app", ['directive.cusTree', 'directive.cnode']);
app.controller("Contrl", function($scope, $http) {
$scope.some = function() {
return $http.get('person.json').success(function(data) {
$scope.nodetree = data;
return data;
});
}
});
})();
person.json
{
"person": [{
"id": 1,
"name": "A1" ,
"child": [{
"id": 1.1,
"name": "A11",
"child": [{
"id": 1.11,
"name": "A111"
}, {
"id": 1.12,
"name": "A112"
}, {
"id": 1.13,
"name": "A113"
}]
}, {
"id": 1.2,
"name": "A12"
}, {
"id": 1.3,
"name": "A13",
"child": [{
"id": 1.31,
"name": "A131"
}, {
"id": 1.32,
"name": "A132"
}, {
"id": 1.33,
"name": "A133"
}]
}]
}, {
"id": 2,
"name": "B2"
}, {
"id": 3,
"name": "C3"
}, {
"id": 4,
"name": "D4"
}
]
}
item.html
<div ng-click="show(show)" ng-init="show=true" class="container" ng-repeat="node in nodedata" ng-if="nodedata.length>0">
<ul>
{{node.name}}
<br>
<div ng-if="node.child.length>0">
<custree nodedata="node.child"> </custree>
</div>
</ul>
</div>
index.html
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="app.js" type="text/javascript"></script>
<script src="cusTree.js" type="text/javascript"></script>
<script src="cnode.js" type="text/javascript"></script>
</head>
<body>
<div ng-controller="Contrl as n">
<div ng-init="nodetree=some()">
<div ng-repeat="node in nodetree">
<div class="container">
<custree nodedata="node"> </custree>
</div>
<br>
</div>
</div>
</div>
</body>
</html>
cusTree.js
angular.module('directive.cusTree',[])
.directive('custree',function(){
return{
restrict :'E',
scope: {
nodedata:'='
},
templateUrl:"item.html",
controller:function($scope){
//console.log("new="+ JSON.stringify($scope.nodedata));
}
};
});
If you are creating tree with AngularJS, you have to create 2 directives as below:
app.directive('nodeTree', function () {
return {
template: '<node ng-repeat="node in tree"></node>',
replace: true,
restrict: 'E',
scope: {
tree: '=children'
}
};
});
app.directive('node', function ($compile) {
return {
restrict: 'E',
replace: true,
templateUrl: 'partials/node.html', // HTML for a single node.
link: function (scope, element) {
/*
* Here we are checking that if current node has children then compiling/rendering children.
* */
if (scope.node && scope.node.children && scope.node.children.length > 0) {
var childNode = $compile('<ul class="tree" ng-if="!node.visibility"><node-tree children="node.children"></node-tree></ul>')(scope);
element.append(childNode);
}
},
controller: ["$scope", function ($scope) {
// This function is for just toggle the visibility of children
$scope.toggleVisibility = function (node) {
node.visibility = !node.visibility;
};
// Here We are marking check/un-check all the nodes.
$scope.checkNode = function (node) {
node.checked = !node.checked;
function checkChildren(c) {
angular.forEach(c.children, function (c) {
c.checked = node.checked;
checkChildren(c);
});
}
checkChildren(node);
};
}]
};
});
For More details you can checkout Github Link, its have working demo.

get selected checkbox value in array

I have created an applicaion in angular for getting all the checkbox value which is checked into an array, without any looping, but after simultaneous checking and un-checking i am getting wrong data within the array
Working Demo
can anyone please give me some solution for this
var app = angular.module('checkbox', []);
app.controller('homeCtrl', function ($scope) {
$scope.selected = [];
$scope.array_ = angular.copy($scope.array);
$scope.list = [{
"id": 1,
"value": "apple",
"checked": false
}, {
"id": 3,
"value": "orange",
"checked": false
}, {
"id": 5,
"value": "pear",
"checked": false
}];
$scope.checkedOrNot = function (id, isChecked, index) {
if (isChecked) {
$scope.selected.push(id);
} else {
$scope.selected.splice(index, 1);
}
}
});
please see here http://jsfiddle.net/7L6beac6/2/
you need to find index of checkbox in selected array and remove it using that index instead of index of checkbox inside reaper
var app = angular.module('checkbox', []);
app.controller('homeCtrl', function ($scope) {
$scope.selected = [];
$scope.array_ = angular.copy($scope.array);
$scope.list = [{
"id": 1,
"value": "apple",
"checked": false
}, {
"id": 3,
"value": "orange",
"checked": false
}, {
"id": 5,
"value": "pear",
"checked": false
}];
$scope.checkedOrNot = function (id, isChecked, index) {
console.log("index:" + index + " " + isChecked);
if (isChecked) {
$scope.selected.push(id);
} else {
var _index = $scope.selected.indexOf(id);
$scope.selected.splice(_index, 1);
}
};
});

Angular Select. Add element and automatically select it

Look ex. jsfiddle example
HTML
<div ng-app="app" ng-controller="mCtrl">
<select size="20" ng-model="selectedType" ng-init="selectedType=types[0]"
ng-options="type.name for type in types">
</select>
<button ng-click="addElem()">add elem in array</button>
</div>
Controller
$scope.types = [ my Array of objects ];
$scope.addElem = function() {
element = {
"id": 999,
"name": "xxx"
};
$scope.types.push(element);
}
I want to add element in ng-options array, and automatically select it in select Box with model changing.
I tried
$scope.selectedType = $scope.types[$scope.types.lenght - 1]
, but it doesn't work.
You have misspelled length.
Here is solution which works:
app = angular.module('app', []);
app.controller('mCtrl', function($scope) {
$scope.types = [
{
"id": 0,
"name": "Zaj"
},
{
"id": 1,
"name": "Emoltra"
},
{
"id": 2,
"name": "Malathion"
},
{
"id": 3,
"name": "Pyramax"
},
{
"id": 4,
"name": "Boink"
},
{
"id": 5,
"name": "Savvy"
},
{
"id": 6,
"name": "Accruex"
},
{
"id": 7,
"name": "Zappix"
}
];
$scope.addElem = function() {
element = {
"id": 7,
"name": "Zappix"
};
$scope.types.push(element);
$scope.selectedType = $scope.types[$scope.types.length - 1];
}
})
DEMO
In your code, there is a typo you have misspelled length
$scope.selectedType = $scope.types[$scope.types.length- 1]
DEMO
OR
You can set it using $scope.selectedType = element
$scope.addElem = function () {
element = {
"id": $scope.types.length + 1,
"name": "Zappix" + $scope.types.length + 1
};
$scope.types.push(element);
$scope.selectedType = element;
}
DEMO

Categories

Resources