How to get the sum of the lengths of all arrays? - javascript

I receive different strings as arguments, there may be several of them.
I check in the if block if there are more than 1 argument, then I need to return the sum of the lengths of the lines that were passed in the function arguments. How can i do this?
const strSum = (...args) => {
let sum = 0;
if (args.length > 1) {
args.forEach((item) => {
});
}
return sum;
};
console.log(strSum('hello', 'hi', 'my name', 'is')); //16

You can add item.length to the sum. item.length will be equals to the length of the string.
const strSum = (...args) => {
let sum = 0;
if (args.length > 1) {
args.forEach((item) => {
sum += item.length
});
}
return sum;
};
console.log(strSum('hello', 'hi', 'my name', 'is')); //16
console.log(strSum()); //0

You can use array.reduce
const strSum1 = (...args) => {
if (args.length <= 1) return 0;
return args.reduce((sum, item) => { return sum + item.length}, 0)
};

Related

Find how many items in array are greater equal or less than given number Javascript

let numbers = [2, 2, 6, 10];
const findAvarage = (numbers) => {
let total = 0;
let checkIntegers = numbers.every(i => !Number.isInteger(i))
if (checkIntegers = true) {
for(let i = 0; i < numbers.length; i++) {
total += numbers[i];
}
let avg = total / numbers.length;
return avg
} else {
return "Only integers allowed"
}
const compareNumbers = (numbers) => {
}
In this code I calculate the avarage of the given numbers in array and now I want to find how many numbers in array are greater that avarage number with second function
I tried to use find method but it did not work out,any solutions on this please?
You can use filter function to filter out the numbers that are larger than average.
const avg = findAvarage(numbers)
const count = numbers.filter(number => number > avg).length
const compareNumbers = (numbers) => {
const avg = findAvarage(numbers);
let greater = 0;
numbers.forEach((num) => { if (num > avg) greater++; });
return greater;
}
u can use filter or reduce to solve it
let numbers = [2, 2, 6, 10];
function countNumbers(number){
return numbers.filter(num=> num>=number).length;
}
function countNumbers2(number){
return numbers.reduce((count,item)=>count+(item>=number),0)
}
console.log(countNumbers(7));
console.log(countNumbers2(3))
Javascript does not provide many extension methods that can be used for arrays, you have just some basics operations.
Your code can be more cleaner if you turn this need into extensions for arrays that you can them every where without calling functions, you can do as follow:
Object.defineProperties(Array.prototype, {
count: {
value: function(value) {
if(isNan(value)) return NaN;
return this.filter(x => x>=value).length;
}
},
average:{
value:function(){
let total = 0;
if(!this.every(i => Number.isInteger(i)))
return NaN;
for(let i = 0; i < numbers.length; i++) {
total += numbers[i];
}
return total/this.length;
}
}
});
and you can use it like this for you example
var result = numbers.count(numbers.average())
this way ?
const findAvarage=(a,b,c,d) => [a,b,c,d].reduceRight((t,n,i,a)=>
{
t += n
if (!i) t /= a.length
return t
},0)
, greaterOrEqualCount = (a,b,c,d) =>
{
let avg = findAvarage(a,b,c,d)
return [a,b,c,d].reduce((r,n)=>r+(n<avg?0:1),0)
}
console.log("count ",greaterOrEqualCount(2,2,6,10))

Take the average of an array items

Try to get average of values. I have json data going inside that, grabbing the array and using the average function on it. But error returns...
TypeError: arr.reduce is not a function
It's from first console.log(myArray) as per screenshot below. and second console.log with avg function, not working...
data() {
return {
myArray:[],
}
},
methods: {
avgArray: function(){
const sum = arr => arr.reduce((a,c) => (a + c));
const avg = arr => sum(arr) / arr.length;
this.estates.forEach((a, index) => {
this.myArray = a.m2_price;
console.log(this.myArray);
});
console.log(avg(this.myArray));
}
}
avgArray: function(){
const sum = arr => arr.reduce((a,c) => (a += c),0); // add equals and init with 0
const avg = arr => sum(arr) / arr.length;
this.myArray = this.estates.map(a => a.m2_price)
console.log(avg(this.myArray));
}
You were setting this.myArray as a value and not an array. You could've either pushed the m2_price or map it like above
Reduce function only exists on arrays. Clearly you were logging this.myArray and getting integers. Hence the error.
That is what reduce is for
const average = array => (array && array.length) ? (array.reduce((sum, item) => sum + item, 0) / array.length) : undefined;
console.log(average([1,2,3,4,5,6]));
export the average function from a file called average.js
Applied to your situation
import { average } from 'pathToYourIncludeLibrary/average';
data() {
return {
myArray:[],
}
},
methods: {
avgArray: () => average(this.myArray)
}

Count of values in javascript

I have homework to write a function that will be called with 2 parameters:
a is a list of numbers.
amount represents the count of the numbers in the array.
The function should return the number in the list that occurs amount times.
For example , if a = [5,5,5,3,2,1,1], and amount = 2, the function should return 1, because there are only two ones in the array. If amount = 3, the function should return 5 , if amount = 6, the function will return 0 since there are numbers that occur six time.
try this one
var max=3;
var array=[5,5,5,3,2,1,1];
console.log(verify(array,max))
function verify(array,max) {
var match=0;
array.map(obj => {
if(array.filter(x => x === obj).length == max)
match= obj;
});
return match;
}
Here is a way to get the values by count using reduce.
Since there may be more than one element matching the count, or even 0, an array is returned.
reduce is used to build a map (object) of the unique items to their counts. We the find the map entries where the counts match, and the keys (unique items) for these entries are returned.
const count = (arr, num) => {
const count = arr.reduce((count, x) => {
count[x] = (count[x] || 0) + 1;
return count;
}, {});
return Object.entries(count)
.filter(([k, v]) => v === num)
.map(([k, v]) => +k);
}
console.log(count([5,5,5,3,2,1,1], 1)); // [2, 3]
console.log(count([5,5,5,3,2,1,1], 3)); // [5]
console.log(count([5,5,5,3,2,1,1], 5)); // []
make a array of unique values from real array. Then loop though it and filter() real array to check the count of elements.
const array = [5,5,5,3,2,1,1]
function count(arr,amount){
const unique = [...new Set(arr)];
for(let item of unique){
if(arr.filter(num => num === item).length === amount)
return item;
}
return 0;
}
console.log(count(array,1));
console.log(count(array,2));
console.log(count(array,3));
console.log(count(array,4));
console.log(count(array,5));
You should use below code.
#RaviTeja's code is giving max number of array but you dont want it. You want to number which is same quantity with your "amount" parameter.This code provides this for you
function findingAmount() {
var numberContainer = [ 2, 3, 2,5,2,3 ];
console.log(findingAmountImp(numberContainer,1)); // result 5
console.log(findingAmountImp(numberContainer,2)); // result 3
console.log(findingAmountImp(numberContainer,3)); // result 2
}
function findingAmountImp(numbers,amount) {
var count=1;
for (i=0; i<numbers.length; i++) {
for (j=0; j<numbers.length; j++) {
if(i===j){
j=j+1;
if(j<numbers.length){
if(numbers[i] === numbers[j])
{
count++;
}
}else{
for(k=0;k<i;k++){
if(numbers[i] === numbers[k])
{
count++;
}
}
}
}else{
if(numbers[i] === numbers[j])
{
count++;
}
}
}
if( count === amount){
return numbers[i]
}
count=1;
}
}

Javascript reduce with condition

How can I use reduce in order to return the sum only if the accumulator (a) and the currentValue (b) is both an Integer?
My guestGroups Array:
"guestGroups":[
{
"bookingNumber":"21.05.201827.05.20181208",
"arrivalDate":"2018-05-19T22:00:00.000Z",
"departureDate":"2018-05-25T22:00:00.000Z",
"customerId":1,
"fields":[
{
"value":"2",
"display_name":"Personen Anzahl",
"servicio_tags":[
"person-number-info"
]
}
],
"number":"041"
}
]
getPersonNumberAdult() {
const personNumberField = this.fields.find(f => {
return f.servicio_tags && f.servicio_tags.includes('person-number-info');
});
return personNumberField ? Number(personNumberField.value.match(/\d+/)[0]) : '-';
}
isInt(value) {
let x = parseFloat(value);
return !isNaN(value) && (x | 0) === x;
}
guestInfo: t.guestGroups
.map(gg => gg.getPersonNumberAdult())
.reduce((function(a, b) {
if (a && b) {
{
if (this.isInt(a) && this.isInt(b)) {
return a + b
} else {
return '-'
}
}
}
}), 0)
This gives me undefined.
Thanks for your efforts!
Your getPersonNumberAdult should not return either a number or a string. It should return an integer or NaN if no number is available. The '-' should only be used in formatting the output in the end.
Once you got that, you can either filter out invalid values and sum the rest:
const sum = t.guestGroups
.map(gg => gg.getPersonNumberAdult())
.filter(v => isInt(v)) // or just !isNaN
.reduce((a, b) => a + b, 0);
or just sum them and then replace NaN by '-' if any value was invalid:
const sum = t.guestGroups
.map(gg => gg.getPersonNumberAdult())
.reduce((a, b) => a + b, 0);
const output = isInt(sum) ? String(sum) : '-';
depending on which behaviour you want.

how to sort data on the basis of count field in data array?

function getFrequency(str){
var sorted = str.split("").sort();
var data = [];
for(var i = 0; i <sorted.length; i++){
var last = data[data.length - 1]
if(last && last.character === sorted[i]) last.count++;
else data.push({character : sorted[i], count: 1});
}
return data;
}
it returns an array that consists of characters and their count. I want to arrange these in descending order of count. What to do?
You could sort the data array and use the property count for taking the delta as return value.
data.sort((a, b) => b.count - a.count);
function getFrequency(str){
var sorted = str.split("").sort(),
data = [],
i,
last;
for (i = 0; i < sorted.length; i++){
last = data[data.length - 1];
if (last && last.character === sorted[i]) {
last.count++;
} else {
data.push({ character: sorted[i], count: 1 });
}
}
return data.sort((a, b) => b.count - a.count);
}
console.log(getFrequency('zzzwwwwwabcdabaa'))
.as-console-wrapper { max-height: 100% !important; top: 0; }
Sort data based on count prop.
function getFrequency(str){
var sorted = str.split("").sort();
var data = [];
for(var i = 0; i <sorted.length; i++){
var last = data[data.length - 1]
if(last && last.character === sorted[i]) last.count++;
else data.push({character : sorted[i], count: 1});
}
data = data.sort(function(a,b){
return b.count - a.count
});
return data;
}
console.log( getFrequency('aaaabddyww') )
You could use reduce() to create an object for each character and add it to an array.
function getFrequency(str) {
var chars = str.split("");
return chars.reduce((a, c) => {
var f = a.find(e => e.character === c);
if (f) f.count++;
else a.push({
character: c,
count: 1
});
return a;
}, []);
}
console.log(getFrequency('zzzwwwwwabcdabaa'))
Reduce the string into an object of characters and counts. Convert to an array using Object.values(), then sort by b.count - a.count:
function getFrequency(str) {
return Object.values(str.split('')
.reduce(function(r, c) {
r[c] = r[c] || { character: c, count: 0 };
r[c].count += 1;
return r;
}, Object.create(null))
).sort(function(a, b) {
return b.count - a.count;
});
}
console.log(getFrequency('who let the dogs out who who'));

Categories

Resources