Angular need to sum the values of array - javascript

I have data in which there are arrays. in the array, there is a value which is claimed_value. I need the sum of all claimed_value of arrays. an example I have array all have the claimed_value. but I need to sum of all the claimed_value which have the status=settled in the array.
this is how I'm calling the API.
getClaims(){
if(this.userFilter.company_id){
let url =
'http://api.igiinsurance.com.pk:8888/insurance_IGItakaful/insurance-
api/get_claims.php?company_id='+this.userFilter.company_id;
}else{
let url =
'http://api.igiinsurance.com.pk:8888/insurance_IGItakaful/insurance-
api/get_claims.php?offset=0&limit=200';
}
this.clientData = this.httpClient.get(url).
subscribe(data => {
console.log(data);
this.data = data.records;
var status = 'settled';
var status2 = 'submitted';
var countsettled = this.data.filter((obj) => obj.status ===
status).length;
var countunsettled = this.data.filter((obj) => obj.status ===
status2).length;
console.log(countsettled);
this.countsettled = countsettled;
console.log(countunsettled);
this.countunsettled = countunsettled;
});
}

Your question is more general javascriptthan angular
You can sum element of array by using the Array.reduce function
You can sum on a specific status by filtering first
Ie
const sum = this.data.filter(item => item.status === 'settled')
.reduce((acc, item) => acc + Number(item.claimed_value), 0);
Note that as said in comment you received a string and not a numberso you must convert it at first (see the Number() function in thereduceclosure)) otherwise the+` operator will just concatenate the string

let finalSum = 0;
this.data.forEach((item) => {
if(item.status === 'settled'){
finalSum += item.claimed_value
}
});
console.log("final sum is ", finalSum);
Hello, This will loop on all the arrays in your data list , and add the number of claimed_value to the finalSum .
Hope this will work for you.

Related

Information about to Array in JAvascript

I would like to get find elements having same characters but in different order in an array. I made javascript below,is there any way to create Javascript function more basic? Can you give me an idea? Thank you in advance..
<p id="demo"></p>
<script>
const arr1 = ["tap", "pat", "apt", "cih", "hac", "ach"];
var sameChars = 0;
var subArr1 = [];
for(var i = 0; i < arr1.length; i++){
for(var j = i+1; j < arr1.length; j++){
if(!subArr1.includes(arr1[i]) && !subArr1.includes(sortAlphabets(arr1[i]))){
subArr1.push(arr1[i]);
sameChars++;
}
if(sortAlphabets(arr1[i]) == sortAlphabets(arr1[j])){
if(!subArr1.includes(arr1[j])){
subArr1.push(arr1[j]);
}
}
}
}
function sortAlphabets(text1) {
return text1.split('').sort().join('');
};
document.getElementById("demo").innerHTML = sameChars;
</script>
I would just use reduce. Loop over split the string, sort it, join it back. Use it as a key in an object with an array and push the items onto it.
const arr1 = ["tap", "pat", "apt", "cih", "hac", "ach"];
const results = arr1.reduce((obj, str) => {
const key = str.split('').sort().join('');
obj[key] = obj[key] || [];
obj[key].push(str);
return obj;
}, {});
console.log(Object.values(results));
You can get the max frequency value by building a map and getting the max value of the values.
const frequencyMap = (data, keyFn) =>
data.reduce(
(acc, val) =>
(key => acc.set(key, (acc.get(key) ?? 0) + 1))
(keyFn(val)),
new Map());
const groupMap = (data, keyFn) =>
data.reduce(
(acc, val) =>
(key => acc.set(key, [...(acc.get(key) ?? []), val]))
(keyFn(val)),
new Map());
const
data = ["tap", "pat", "apt", "cih", "hac", "ach"],
sorted = (text) => text.split('').sort().join(''),
freq = frequencyMap(data, sorted),
max = Math.max(...freq.values()),
groups = groupMap(data, sorted);
document.getElementById('demo').textContent = max;
console.log(Object.fromEntries(freq.entries()));
console.log(Object.fromEntries(groups.entries()));
.as-console-wrapper { top: 2em; max-height: 100% !important; }
<div id="demo"></div>
Maybe split the code into two functions - one to do the sorting and return a new array, and another to take that array and return an object with totals.
const arr = ['tap', 'pat', 'apt', 'cih', 'hac', 'ach'];
// `sorter` takes an array of strings
// splits each string into an array, sorts it
// and then returns the joined string
function sorter(arr) {
return arr.map(str => {
return [...str].sort().join('');
});
}
// `checker` declares an object and
// loops over the array that `sorter` returned
// creating keys from the strings if they don't already
// exist on the object, and then incrementing their value
function checker(arr) {
const obj = {};
for (const str of arr) {
// All this line says is if the key
// already exists, keep it, and add 1 to the value
// otherwise initialise it with 0, and then add 1
obj[str] = (obj[str] || 0) + 1;
}
return obj;
}
// Call `checker` with the array from `sorter`
console.log(checker(sorter(arr)));
<p id="demo"></p>
Additional documentation
map
Loops and iteration
Spread syntax

A number which has same frequency of all integers present

I want to check if all the integers present in a number has the same frequency.
Sample Input :
1212
Sample Output :
True
I am able to get the frequency using reduce function . But not able to compare the values.
let countOccurrences = arr => arr.reduce((accm,x)=> (accm[x] = ++accm[x] || 1,accm),{});
var obj = (countOccurrences([2,3,4,2,3,4]))
for(var i in obj)
console.log(obj[i+1]);
if(obj[i]===obj[i+1]){
console.log("true");
}else{
console.log("false");
}
//end-here
});
One way would be to use the Array every() method to check that every value in your object is equal to the first one (after converting to an array of values).
const countOccurrences = arr => arr.reduce((accm,x)=> (accm[x] = ++accm[x] || 1,accm),{});
const obj = countOccurrences([2,3,4,2,3,4]);
const same = Object.values(obj).every((el, _, arr) => el === arr[0]);
console.log(same);
You can use Set to remove dupicates
let countOccurrences = arr => arr.reduce((accm,x)=> (accm[x] = ++accm[x] || 1,accm),{});
var obj = (countOccurrences([2,3,4,2,3,4]));
const isSameFrequency = (new Set(Object.values(obj))).size == 1;
console.log(isSameFrequency);

Delete all occurrence of duplicate values in an array in javascript/jquery

I am trying to work on a problem where I want to remove all the occurrences of similar value in an array
eg.
var sampleArr = ["mary","jane","spiderman","jane","peter"];
and I am trying to get result as => ["marry","spiderman","peter"]
how do I get this?
You can use filter()
var arr = ["mary","jane","spiderman","jane","peter"];
var unique = arr.filter((x, i) => arr.indexOf(x) === i);
console.log(unique);
var sampleArr = ["mary","jane","spiderman","jane","peter"];
var unique = [];
var itemCount = {};
sampleArr.forEach((item,index)=>{
if(!itemCount[item]){
itemCount[item] = 1;
}
else{
itemCount[item]++;
}
});
for(var prop in itemCount){
if(itemCount[prop]==1){
unique.push(prop);
}
}
console.log(unique);
Check this.
You can count the frequency of the character and just pick the character whose frequency is 1.
const arr = ["mary","jane","spiderman","jane","peter"];
frequency = arr.reduce((o,ch) => {
o[ch] = (o[ch] || 0) + 1;
return o;
}, {}),
unique = Object.keys(frequency).reduce((r,k) => frequency[k] === 1? [...r, k]: r, []);
console.log(unique);
You can use filter:
var sampleArr = ["mary","jane","spiderman","jane","peter"];
var result = sampleArr.filter((e,_,s)=>s.filter(o=>o==e).length<2);
// or with reduce and flatmap
const result1 = Object.entries(sampleArr.reduce((a,e)=>(a[e]??=0, a[e]++, a),{})).flatMap(([k,v])=>v==1 ? k: []);
console.log(result)
console.log(result1);
lot of solution, here easy solution to understand using match to have the occurence and filter to eliminate:
var arr = ['ab','pq','mn','ab','mn','ab'];
var st = arr.join(",");
result = arr.filter(it => {
let reg = new RegExp(it, 'g');
return st.match(reg).length == 1;
});
console.log(result);// here ["pq"]
filter seems to be your best bet here if you need extremely robust performance. No real need for jQuery in this instance. Personally, I would opt for readability for something like this and instead sort, set duplicates to null, and then remove all null values.
var sampleArr = ["mary","jane","spiderman","jane","peter"];
var result = sampleArr.sort().forEach((value, index, arr) => {
// if the next one is the same value,
// set this one to null
if(value === arr[value + 1])
return arr[index] = null;
// if the previous one is null, and the next one is different,
// this is the last duplicate in a series, so should be set to null
if(arr[value - 1] === arr[index + 1] !== value)
return arr[index] = null;
return
})
.filter(value => value === null) //remove all null values
console.log(result);

in the easiest and most concise way as possible

I want to sort an array values in an ascending or descending order without using sort().
I have created a function, however I am not satisfied with it.
I believe the code below could be much shorter and more concise.
Please let me know where to modify or you may entirely change the code too. Thank you in advance.
const func = arg => {
let flip = false;
let copy = [];
for(let val of arg) copy[copy.length] = val;
for(let i=0; i<arg.length; i++) {
const previous = arg[i-1];
const current = arg[i];
if(previous > current) {
flip = true;
copy[i] = previous;
copy[i-1] = current;
}
}
if(flip) return func(copy);
return copy;
};
l(func([5,2,8,1,9,4,7,3,6]));
If your input is composed of whole numbers, as in the example, pne option is to reduce the array into an object, whose keys are the numbers, and whose values are the number of times those values have occured so far. Then, iterate over the object (whose Object.entries will iterate in ascending numeric key order, for whole number keys), and create the array to return:
const func = arr => {
const valuesObj = {};
arr.forEach((num) => {
valuesObj[num] = (valuesObj[num] || 0) + 1;
});
return Object.entries(valuesObj)
.flatMap(
([num, count]) => Array(count).fill(num)
);
};
console.log(
func([5,2,8,1,9,10,10,11,4,7,3,6])
);
This runs in O(N) time.
To account for negative integers as well while keeping O(N) runtime, create another object for negatives:
const func = arr => {
const valuesObj = {};
const negativeValuesObj = {};
arr.forEach((num) => {
if (num >= 0) valuesObj[num] = (valuesObj[num] || 0) + 1;
else negativeValuesObj[-num] = (negativeValuesObj[-num] || 0) + 1;
});
return [
...Object.entries(negativeValuesObj).reverse()
.flatMap(
([num, count]) => Array(count).fill(-num)
),
...Object.entries(valuesObj)
.flatMap(
([num, count]) => Array(count).fill(num)
)
];
};
console.log(
func([5,2,8,1,-5, -1, 9,10,10,11,4,7,3,6, -10])
);
For non-integer items, you'll have to use a different algorithm with higher computational complexity.

Browse through an array for a specific amount of values

I have an array like this:
var arr = [a,a,b,b,b,c]
The result(a new array) should only show all the values which are exactly 2 times in this array, e.g.: a
Do you guys know how I could realize this? Thanks
Please try this code:
var arr = ['a','a','b','b','b','c'];
var numberOfOccurrences = {};
arr.forEach(function (item) {
numberOfOccurrences[item] = (numberOfOccurrences[item] || 0) + 1;
});
var duplicates = Object.keys(numberOfOccurrences).filter(function (item) { return numberOfOccurrences[item] === 2 });
console.log(duplicates);
You can first create object and add properties with forEach loop and then use filter on Object.keys to return array as result.
var arr = ['a','a','b','b','b','c'];
var o = {}
arr.forEach(e => o[e] = (o[e] || 0) + 1);
var result = Object.keys(o).filter(e => o[e] == 2);
console.log(result)

Categories

Resources