I am quite new to AngularJS and have been building the following:
app.js
$scope.inkomsten= [
{ name: 'Salaris',value:'500' },
{ name: 'Toeslag',value:'200' },
{ name: 'Inkomsten',value:'211' },
{ name: 'Weekend', value:'22' }
];
$scope.uitgiften= [
{ name: 'eten',value:'120'},
{ name: 'kat',value:'230'},
{ name: 'schildpad', value: '300'},
{ name: 'huur', value: '200'}
];
Now I would like to take the values of both of these object and substract them from each other!
So either have all the values of Inkomsten added to another and the ones from Uitgiften.. and then substract or individually(Which is prefered... So taking the value of uitgiften and then from inkomsten and substract them.)
I have been tinkering around with it but I can't seem to find a solution for it. Anyways, not in Angular :D
I hope you guys can help
Clarification:
Sorry. I would like to have
uitgiften.value[1]+uitgiften.value[2]+uitgiften.value[3]
and then inkomsten.value[1]+inkomsten.value[2]+inkomsten.value[3]
and then the outcome of these 2 summs would need to be outcomeInkomsten-outcomeUitgiften=endOutcome
Since your values are strings, you will need to cast them to numbers. Here's what I would do:
var result = 0;
$scope.inkomsten.forEach(function(item){
result += Number(item.value);
});
$scope.uitgiften.forEach(function(item){
result -= Number(item.value);
});
Since it is an array you could add a function to the Array prototype.
$scope.inkomsten= [
{ name: 'Salaris',value:'500' },
{ name: 'Toeslag',value:'200' },
{ name: 'Inkomsten',value:'211' },
{ name: 'Weekend', value:'22' }
];
$scope.uitgiften= [
{ name: 'eten',value:'120'},
{ name: 'kat',value:'230'},
{ name: 'schildpad', value: '300'},
{ name: 'huur', value: '200'}
];
Array.prototype.sum = function (prop) {
var total = 0;
for ( var i = 0, _len = this.length; i < _len; i++ ) {
total += parseInt(this[i][prop]);
}
return total;
}
$scope.endOutcome = $scope.inkomsten.sum("value") - $scope.uitgiften.sum("value");
The Fiddle:
http://jsfiddle.net/U3pVM/20778/
you can use array method reduce:
var $scope={};
$scope.inkomsten= [
{ name: 'Salaris',value:'500' },
{ name: 'Toeslag',value:'200' },
{ name: 'Inkomsten',value:'211' },
{ name: 'Weekend', value:'22' }
];
var res = $scope.inkomsten.reduce(function(total, current){
return total + Number(current.value);
}, 0)
console.log(res)
this will give you the numeric total of an Array;
and then you can do the same with second array, and subtract the two;
well you can use
var results=0;
for(i=0;i<$scope.inkomsten.length;i++){
results+=Number($scope.inkomsten[i].value);
}
for(i=0;i<$scope.uitgiften.length;i++){
results-=Number($scope.uitgiften[i].value);
}
console.log(results);
You can try this below code
$scope.inkomsten= [
{ name: 'Salaris',value:'500' },
{ name: 'Toeslag',value:'200' },
{ name: 'Inkomsten',value:'211' },
{ name: 'Weekend', value:'22' }
];
$scope.uitgiften= [
{ name: 'eten',value:'120'},
{ name: 'kat',value:'230'},
{ name: 'schildpad', value: '300'},
{ name: 'huur', value: '200'}
];
$scope.sum1 = 0;
$scope.sum2 = 0;
for(i in $scope.inkomsten){
$scope.sum1 = $scope.sum1 + parseInt($scope.inkomsten[i].value);
}
for(i in $scope.uitgiften){
$scope.sum2 = $scope.sum2 + parseInt($scope.uitgiften[i].value);
}
$scope.endOutcome = $scope.sum1 - $scope.sum2;
alert($scope.endOutcome);
Related
I need to call transformResponse many times based persons array. But the following code call only the last index
function fill() {
var persons = [
{ id: 34, text: $translate.instant("enter") },
{ id: 36, text: $translate.instant("high") },
{ id: 53, text: $translate.instant("graduates") },
{ id: 35, text: $translate.instant("persons") },
]
var personSubCategoriesList = [];
for (var i = 0; i < persons.length; i++) {
$scope.remote = {
url: window.config.apiHostUrl + `lookup/Get?id=${persons[i].id}`,
transformResponse: function (data) {
var personSubCategories = angular.fromJson(data);
angular.forEach(personSubCategories, function (personSubCategoriesObjet) {
var categories = { name: personSubCategoriesObjet.localizedName, code: personSubCategoriesObjet.id };
personSubCategoriesList.push(categories);
});
return personSubCategoriesList.map(function (adminCategories) {
return {
name: adminCategories.name,
code: adminCategories.code
};
});
}
};
}
}
I found the solution by using observable $q
I've taken the following sample from a different question. And I am able to identify the object. But I also need to find our the position of that object. For example:
var arr = [{
Id: 1,
Categories: [{
Id: 1
},
{
Id: 2
},
]
},
{
Id: 2,
Categories: [{
Id: 100
},
{
Id: 200
},
]
}
]
If I want to find the object by the Id of the Categories, I can use the following:
var matches = [];
var needle = 100; // what to look for
arr.forEach(function(e) {
matches = matches.concat(e.Categories.filter(function(c) {
return (c.Id === needle);
}));
});
However, I also need to know the position of the object in the array. For example, if we are looking for object with Id = 100, then the above code will find the object, but how do I find that it's the second object in the main array, and the first object in the Categories array?
Thanks!
Well, if every object is unique (only in one of the categories), you can simply iterate over everything.
var arr = [{
Id: 1,
Categories: [{Id: 1},{Id: 2}]
},
{
Id: 2,
Categories: [{Id: 100},{Id: 200}]
}
];
var needle = 100;
var i = 0;
var j = 0;
arr.forEach(function(c) {
c.Categories.forEach(function(e) {
if(e.Id === needle) {
console.log("Entry is in position " + i + " of the categories and in position " + j + " in its category.");
}
j++;
});
j = 0;
i++;
});
function findInArray(needle /*object*/, haystack /*array of object*/){
let out = [];
for(let i = 0; i < haystack.lenght; i++) {
if(haystack[i].property == needle.property) {
out = {pos: i, obj: haystack[i]};
}
}
return out;
}
if you need the position and have to filter over an property of the object you can use a simple for loop. in this sample your result is an array of new object because there can be more mathches than 1 on the value of the property.
i hope it helps
Iterate over the array and set index in object where match found
var categoryGroups = [{
Id : 1,
Categories : [{
Id : 1
}, {
Id : 2
},
]
}, {
Id : 2,
Categories : [{
Id : 100
}, {
Id : 200
},
]
}
]
var filterVal = [];
var needle = 100;
for (var i = 0; i < categoryGroups.length; i++) {
var subCategory = categoryGroups[i]['Categories'];
for (var j = 0; j < subCategory.length; j++) {
if (subCategory[j]['Id'] == findId) {
filterVal.push({
catIndex : i,
subCatIndex : j,
id : needle
});
}
}
}
console.log(filterVal);
Here is solution using reduce:
var arr = [{ Id: 1, Categories: [{ Id: 1 }, { Id: 2 }, ] }, { Id: 2, Categories: [{ Id: 100 }, { Id: 200 }, ] } ]
const findPositions = (id) => arr.reduce((r,c,i) => {
let indx = c.Categories.findIndex(({Id}) => Id == id)
return indx >=0 ? {mainIndex: i, categoryIndex: indx} : r
}, {})
console.log(findPositions(100)) // {mainIndex: 1, categoryIndex: 0}
console.log(findPositions(1)) // {mainIndex: 0, categoryIndex: 0}
console.log(findPositions(200)) // {mainIndex: 1, categoryIndex: 1}
console.log(findPositions(0)) // {}
Beside the given answers with fixt depth searh, you could take an recursive approach by checking the Categories property for nested structures.
function getPath(array, target) {
var path;
array.some(({ Id, Categories = [] }) => {
var temp;
if (Id === target) {
path = [Id];
return true;
}
temp = getPath(Categories, target);
if (temp) {
path = [Id, ...temp];
return true;
}
});
return path;
}
var array = [{ Id: 1, Categories: [{ Id: 1 }, { Id: 2 },] }, { Id: 2, Categories: [{ Id: 100 }, { Id: 200 }] }];
console.log(getPath(array, 100));
.as-console-wrapper { max-height: 100% !important; top: 0; }
I am building an object from a form that is currently rendered server side. I collect all the check boxes displayed in the image below and I am trying to sort them in a way that all the check boxes under each step (1, 2, 3 etc) is a single object based on the property parentNode.
Currently the document.querySelectorAll('.checkboxes') fetches all the checkboxes in following format.
var newObj = [
{
name: 'one',
parentNode: {
id: 'stepOne'
}
},
{
name: 'two',
parentNode: {
id: 'stepTwo'
}
},
{
name: 'three',
parentNode: {
id: 'stepOne'
}
},
]
The new object should be:
var newObj = {
stepOne: [
{
name: 'one',
parentNode: {
id: 'stepOne'
}
},
{
name: 'three',
parentNode: {
id: 'stepOne'
}
},
],
stepTwo: [
{
name: 'two',
parentNode: {
id: 'stepTwo'
}
},
]
}
Usually I do something like this:
let stepOne = function(step) {
return step.parentNode.getAttribute('id') === 'stepOne';
}
let stepTwo = function(step) {
return step.parentNode.getAttribute('id') === 'stepTwo';
}
let allTheStepOnes = fetchCheckBoxes.filter(stepOne);
But filter doesn't work on dom object and this seems inefficient as well.
Proper way of doing this is a forEach loop and using associative arrays like this:
let newObject = {};
originalObject.forEach((item)=>{
let step = item.parentNode.id
if (newObj[step] === undefined) {
newObj[step] = []
}
newObj[step].push(item)
})
Using reduce we can reduce your current array into the new structure.
return newObj.reduce(function(acc, item) {
If acc[item.parentNode.id] has been defined before, retrieve this. Otherwise set it to an empty array:
acc[item.parentNode.id] = (acc[item.parentNode.id] || [])
Add the item to the array and then return it:
acc[item.parentNode.id].push(item);
return acc;
We set the accumulator as {} to start with.
Snippet to show the workings.
var newObj = [{
name: 'one',
parentNode: {
id: 'stepOne'
}
}, {
name: 'two',
parentNode: {
id: 'stepTwo'
}
}, {
name: 'three',
parentNode: {
id: 'stepOne'
}
}, ];
var newOrder = function(prevList) {
return prevList.reduce(function(acc, item) {
acc[item.parentNode.id] = (acc[item.parentNode.id] || [])
acc[item.parentNode.id].push(item);
return acc;
}, {});
}
console.log(newOrder(newObj));
This function should do the trick
function mapObj(obj) {
var result = {};
for(var i = 0; i < obj.length; i++) {
var e = obj[i];
result[e.parentNode.id] = result[e.parentNode.id] || [];
result[e.parentNode.id].push(e);
}
return result;
}
I have this array:
var itemList = [
{
image: "images/home.jpg",
name: "Home"
},
{
name: "Elvis",
},
{
name: "Jonh"
},
{
image: "images/noah.jpg",
name: "Noah"
},
{
name: "Turtle"
}
]
How can I organize the array to objects with image property come first, so that it looks like this?:
var itemList = [
{
image: "images/home.jpg",
name: "Home"
},
{
image: "images/noah.jpg",
name: "Noah"
},
{
name: "Elvis",
},
{
name: "Jonh"
},
{
name: "Turtle"
}
]
This code put at the beginning elements that have the property 'image'. Other elements stay in the same order.
function compare(a,b) {
if ('image' in a) {
return 1;
} else if ('image' in b) {
return -1;
} else {
return 0;
}
}
itemList.sort(compare);
Try this:
function compare(a,b) {
if (a.image && b.image)
return 0;
if (a.image)
return 1;
return -1;
}
objs.sort(compare);
A bit late, but an alternative:
itemList.sort(function(e1,e2){ return (e1.image === undefined) - (e2.image === undefined); });
I have a Object to dynamically fill my DropDown list.
var myOptions = [
{ name: Projekte[1][1], value: "val1" },
{ name: Projekte[2][1], value: "val2" },
{ name: Projekte[3][1], value: "val3" },
{ name: Projekte[4][1], value: "val4" },
{ name: Projekte[5][1], value: "val5" },
{ name: Projekte[6][1], value: "val6" },
{ name: Projekte[7][1], value: "val7" },
{ name: Projekte[8][1], value: "val8" },
{ name: Projekte[9][1], value: "val9" },
{ name: Projekte[10][1], value: "val10" }
];
it looks like ther will be up to 100 Projects when the code is in charge, so how can I set name and value of this Object to the right length?
what i tried before was this:
var anzahlproj =100; //how many project i get
var myOptions = [
{ name: Projekte[1][1], value: "val1" }
];
for(var i=2;i<anzahlproj + 1; i++){
myOptions[name] +="Projekte["+i+"][1]",
myOptions[value] += "val"+i;
}
add something to a normal Object is no problem, but how can I add something with multiple elements?
I use: JQuery 1.11.1, JQuery Mobile 1.4.3
var myOptions = [], i;
for (i = 1; i <= 100; i++) {
myOptions.push({name: Projekte[i][1], value: "val" + i});
}
Try this code
var anzahlproj = 100; //how many project i get
for (var i = 2; i < anzahlproj + 1; i++) {
var myOption = new Option(Projekte[i][1], "val" + i.toString());
myOptions.append($(myOption));
}