I'm trying to write a function that will be called with an array that has information on a person such as their name and then age. I need this function to grab all of the numbers only and then return them then added up. I've done some research and it seems filter and reduce are what I need to do this in the easiest way for a total beginner like me to do?
Apologies for any typos/wrong jargon as my dyslexia gets the better of me sometimes.
An example of what kind of array is being passed into the function when called;
{ name: 'Clarie', age: 22 },
{ name: 'Bobby', age: 30 },
{ name: 'Antonio', age: 40 },
Would return the total added numbers.
// returns 92
Why isn't the array I'm calling this function with working? Can you provide me a working example without the array being hardcoded like the other answers? - I'm passing in an array to the function. The main objective is to grab any number from the passed in array and add them together with an empty array returning 0.
function totalNums(person) {
person.reduce((a,b) => a + b, 0)
return person.age;
}
console.log(totalNums([]))
You need to save the result into a new variable then console.log() it like this
const arr= [{ name: 'Clarie', age: 22 },
{ name: 'Bobby', age: 30 },
{ name: 'Antonio', age: 40 },...
];
function totalNums(person) {
let res = person.reduce((a,b) => a + b.age, 0)
return res;
}
console.log(totalNums(arr));
and this is why it has to be like that
.reduce()
js methods like .map(), .filter(), .reduce() and some others, they return a new array, they don't modify the original array.
You can console.log(arr); and you will get this output:
[{ name: 'Clarie', age: 22 },
{ name: 'Bobby', age: 30 },
{ name: 'Antonio', age: 40 },...
];
Your original array unchanged even after running your function so in order to get the result you expect, you need to store it inside a new variable
You need to save the result of your reduce.
For example with array of numbers you would do:
function totalNums(person) {
let res = person.reduce((a,b) => a + b, 0)
return res;
}
console.log(totalNums([5,6,4]))
And for your example you would like to do something like this:
function totalNums(person) {
let res = person.reduce((a,b) => a + b.age, 0)
return res;
}
console.log(totalNums([
{ name: 'Clarie', age: 22 },
{ name: 'Bobby', age: 30 },
{ name: 'Antonio', age: 40 }
]))
function totalNums(person) {
person.reduce((a,b) => a + b, 0)
return person.age;
}
console.log(totalNums([]))
Talking about the function you have created it is incorrect because:
return person.age; Here you are passing an array to function and then accessing it like it's an object.
person.reduce((a,b) => a + b, 0) you can't add a and b because b is an object.
You are not storing value which reduce function will return.
Solution Below :
The reduce function always returns something It never makes changes in the original array.
function totalNums(persons) {
const totalAge = persons.reduce((total, person) => total + person.age, 0);
return totalAge;
}
const persons = [
{ name: "Clarie", age: 22 },
{ name: "Bobby", age: 30 },
{ name: "Antonio", age: 40 },
];
console.log(totalNums(persons));
You can replace total and person with a and b respectively in the above code snippet for your reference.
Related
I need to check that an Array contains an Object that matches a given structure.
I already tried this:
const myArray = [{ name: 'Mete', age: 19, phone: '123456' }];
expect(myArray).toEqual(
expect.arrayContaining([
expect.objectContaining({
name: 'Mete',
age: 19
})
])
)
// Throws no error
It should not match because the object in the array has an additional property "phone".
I need something like toStrictEqual() combined with arrayContaining().
You can use Array.prototype.some() with .toEqual(value) to test each object in the array, which will stop iteration and return true on the first assertion that passes the expectation. Otherwise, false will be returned and the final expect statement will fail.
The technique here is to catch the exceptions thrown from the assertions and convert them to false results:
const expected = {name: 'Mete', age: 19};
const myArray = [{ name: 'Mete', age: 19, phone: '123456' }];
const found = myArray.some(obj => {
try {
expect(obj).toEqual(expected);
return true;
}
catch {
return false;
}
});
expect(found).toBeTruthy();
With every array function, you can get the result:
const strictlyEquals = (arr, props) => arr.every(o=>Object.keys(o).every(i=>props.includes(i)));
console.log(strictlyEquals([{name:'Test', age: 20}], ['name', 'age']));
console.log(strictlyEquals([{name:'Test', age: 20, phone:'Test'}], ['name', 'age']));
If you have to match complete object then:
const strictlyEquals = (arr, props) => arr.every(o=> Object.keys(o).length===Object.keys(props).length && Object.keys(o).every(i=>o[i]===props[i]));
console.log(strictlyEquals([{name:'Test', age: 20},{name:'Test', age: 20}], {name:'Test', age: 20}));
I need to create a record but I have to check whether in the given list record with same name is available or not if available then append with incremented number. Below is the given list.
let listOfValues = [
{
name: "Peter",
age: 25
},
{
name: "Paul",
age: 35
},
{
name: "Paul-1",
age: 35
},
{
name: "Dom",
age: 28
}
]
And, I am creating a record as below:
let requestBody = {
name: "Paul",
age: 28
}
Now, I want to compare name from requestBody with the given list. Suppose, Paul is already available then it will check if Paul-1 is also available then it should increment with one number like Paul-2. Any help would be appreciated.
Generic Solution
Generate a Regex to check a string that starts with the name in the requestBody.
Filter down the list by searching for the names matching the Regex.
You should split the names on "-" and return the index from the name.
Sort the index list so that the largest index is at the end of the list.
Check length of the list filtered out, if its zero, you can directly push.
If its one you can push the element by appending 1 to the name.
If its greater than one increment the last index and append it to name and push.
Working Fiddle
let listOfValues = [
{ name: "Peter", age: 25 },
{ name: "Paul", age: 35 },
{ name: "Paul-1", age: 35 },
{ name: "Dom", age: 28 }
];
let requestBody = {
name: "Paul",
age: 28
}
const regex = new RegExp('^' + requestBody.name.split('-')[0], 'i');
const existingList = listOfValues.filter((item) => item.name.match(regex)).map((item) => +item.name.split('-')[1]).sort((a, b) => a - b);
if (existingList.length > 0) {
const finalIndex = existingList[existingList.length - 1];
listOfValues.push({ name: finalIndex ? `${requestBody.name.split('-')[0]}-${(finalIndex + 1)}` : `${requestBody.name}-1`, age: requestBody.age });
} else {
listOfValues.push(requestBody);
}
console.log(listOfValues);
let arr = [{ age: 3 }, { age: 5 }, { age: 6 }, { age: 7 }];
let exists = arr.find(x => x.age < 4);
exists.age += 1;
console.log(arr);
//output is [{age:4},{age:5},{age:6},{age:7}];
In the above example, I'm updating the result returned by the find method but it also changes the value of the original array why so?
It's because Objects in JavaScript are passed by reference, you got that object ( {age : 3} ) in exists then added 1 to it's "age" key , so the original object also changed .
let obj1 = {age: 3 , name: 'jack' }
let obj2 = obj1
console.log(obj1 === obj2 ) // true
// if you change the second object , the first one will change too :
obj2.age = 15
console.log(obj1 , obj2 )
// obj1 = { age: 15 , name: 'jack' }
// obj2 = { age: 15 , name: 'jack' }
Array.prototype.find will return the first element that satisfy the condition that you've passed as a callback function.
Since you are looking for an object whose age property is less than 4. So It will return first object(whose age is 3). So if you gonna check for equality of exists and arr[0] then It will return object that satisfy the condition
let arr = [{ age: 3 }, { age: 5 }, { age: 6 }, { age: 7 }];
let exists = arr.find((x) => x.age < 4);
console.log(exists === arr[0])
So, If you are going to do any kind of mutation with the object that is returned by the find method then the original object will reflect the changes.
Because both are same object just different references.
If you don't want to mutate the original object then you should clone it before doing any kind of changes to that object.
Note: Both of the following method does shallow copy
1) Using spread syntax
let arr = [{ age: 3 }, { age: 5 }, { age: 6 }, { age: 7 }];
let exists = arr.find((x) => x.age < 4);
const clone = { ...exists };
clone.age += 1;
console.log(arr);
/* This is not a part of answer. It is just to give the output full height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }
2) Using Object.assign
let arr = [{ age: 3 }, { age: 5 }, { age: 6 }, { age: 7 }];
let exists = arr.find((x) => x.age < 4);
const clone = Object.assign({}, exists);
clone.age += 1;
console.log(arr);
Because you have an array of object references. In JavaScript, objects are actually stored elsewhere (called the "heap") and object variables actually only contain the references to object. So the reason is because you're updating the same object.
If you want to do a shallow clone of an object, you can use Object.assign({}, obj).
Further, not directly relevant to your question, if your object properties themselves were to contain other object references, including arrays, and you want those to be copies as well, you'll have to deep-clone them. This is not automatically done by a stock JavaScript function or method. You'll have to find code that does that for you or write it yourself. Last time I did this, I used randa's clone function because a different developer on my team had already imported the ramda library into our project. What makes the most sense for your project may be different.
I want to use linq.js to group the following data by date.
data2 = [{
"date": 1399298400.0,
"adId": 1057946139383,
"impressions": 1000000
}, {
"date": 1399298400.0,
"adId": 3301784671323,
"impressions": 535714
}...... etc.
];
Here's my attempt:
var linq = Enumerable.From(data2);
data2 = linq.GroupBy(function (x) {
return x.date;
}).Select(function (x) {
return {
date: x.Key(),
impressions: x.Sum(function (y) {
return y.impressions | 0;
})
};
}).ToArray();
However, It's not working correctly because the sum of all the impressions before and after the GroupBy are close but not identical.
What is the correct way to use group by in linq.js in this case?
Here's an example in fiddle with full dataset here which alerts the total impressions before and after using the GroupBy.
Solution
You can do this by passing a callback as the third parameter like this:
var grouped = Enumerable.from(dataArray).groupBy("$.person", null, (key, g) => {
return {
person: key,
likes: g.sum("$.likes | 0")
}
}).toArray()
Explanation
In groupBy, the third parameter allows you to modify the results before emitting:
In JS, the bitwise or operator (a single pipe |) returns the first value if it exists, otherwise it returns the second one. Without it, trying to sum an undefined value with a real one, will return NaN
undefined + 1 // NaN
Without | 0, the result would look like this:
This example uses shorthand syntax, but if you prefer anytime you see a string with a dollar sign, you can replace it with the lambda syntax like this (they both do the same exact thing):
// Shorthand
.Select("$.impressions")
// Lambda
.Select(function (x) { return x.impressions })
Working demo with Stack Snippets:
var dataArray = [
{
person: "james",
likes: 100
},
{
person: "james",
likes: 250
},
{
person: "kyle",
likes: 300
},
{
person: "kyle"
//,likes: 450
}
];
var grouped = Enumerable.from(dataArray).groupBy("$.person", null, (key, g) => {
return { person: key, likes: g.sum("$.likes | 0") }
}).toArray()
console.log(grouped);
<script src="https://unpkg.com/linq#3.2.0/linq.js"></script>
Further Reading:
SO - linqjs group by with a sum
I am the author of the open source project http://www.jinqJs.com. You can easily do that in jinqJs like this:
jinqJs().from(data2).groupBy('date').sum('impressions').select();
Let me know if I can be of anymore help.
You might try to group by date.toString(). Might be safer due to how JS evaluates dates equality
Alternatively, people coming into this question might have zero to a lot of buy in using linq.js.
If you're already pulling it in, go for it, but if this is the first couple real use cases for it, it's worth noting that you can accomplish the same thing in vanilla js:
For this data:
var dataArray = [
{ person: "james", likes: 100 },
{ person: "james", likes: 250 },
{ person: "kyle", likes: 300 },
{ person: "kyle" }
];
You can build an object with properties for each key / person and keep summing the values of those props
var obj = dataArray.reduce((acc, cur) => {
acc[cur.person] = (acc[cur.person] || 0) + (cur.likes || 0)
return acc
}, {})
If you want that to be an array of objects, you can convert from an object to array like this
var array = Object.entries(obj).map(entry => {
return { person: entry[0], likes: entry[1] }
})
Can someone explain in simple terms how reduce function with its arguments reduceAdd, reduceSum, reduceRemove works in crossfilter?
Remember that map reduce reduces a dataset by keys of a particular dimension. For example lets use a crossfilter instance with records:
[
{ name: "Gates", age: 57, worth: 72000000000, gender: "m" },
{ name: "Buffet", age: 59, worth: 58000000000, gender: "m" },
{ name: "Winfrey", age: 83, worth: 2900000000, gender: "f" },
{ name: "Bloomberg", age: 71, worth: 31000000000, gender: "m" },
{ name: "Walton", age: 64, worth: 33000000000, gender: "f" },
]
and dimensions name, age, worth, and gender. We will reduce the gender dimension using the reduce method.
First we define the reduceAdd, reduceRemove, and reduceInitial callback methods.
reduceInitial returns an object with the form of the reduced object and the initial values. It takes no parameters.
function reduceInitial() {
return {
worth: 0,
count: 0
};
}
reduceAdd defines what happens when a record is being 'filtered into' the reduced object for a particular key. The first parameter is a transient instance of the reduced object. The second object is the current record. The method will return the augmented transient reduced object.
function reduceAdd(p, v) {
p.worth = p.worth + v.worth;
p.count = p.count + 1;
return p;
}
reduceRemove does the opposite of reduceAdd (at least in this example). It takes the same parameters as reduceAdd. It is needed because group reduces are updated as records are filtered and sometimes records need to be removed from a previously computed group reduction.
function reduceRemove(p, v) {
p.worth = p.worth - v.worth;
p.count = p.count - 1;
return p;
}
Invoking the reduce method would look like this:
mycf.dimensions.gender.reduce(reduceAdd, reduceRemove, reduceInitial)
To take a peek at the reduced values, use the all method. To see the top n values use the top(n) method.
mycf.dimensions.gender.reduce(reduceAdd, reduceRemove, reduceInitial).all()
The returned array would (should) look like:
[
{ key: "m", value: { worth: 161000000000, count: 3 } },
{ key: "f", value: { worth: 35000000000, count: 2 } },
]
The goals of reducing a dataset is to derive a new dataset by first grouping records by common keys, then reducing a dimension those groupings into a single value for each key. In this case we grouped by gender and reduced the worth dimension of that grouping by adding the values of records that shared the same key.
The other reduceX methods are convience methods for the reduce method.
For this example reduceSum would be the most appropriate replacement.
mycf.dimensions.gender.reduceSum(function(d) {
return d.worth;
});
Invoking all on the returned grouping would (should) look like:
[
{ key: "m", value: 161000000000 },
{ key: "f", value: 35000000000 },
]
reduceCount will count records
mycf.dimensions.gender.reduceCount();
Invoking all on the returned grouping would (should) look like:
[
{ key: "m", value: 3 },
{ key: "f", value: 2 },
]
Hope this helps :)
Source: https://github.com/square/crossfilter/wiki/API-Reference
http://blog.rusty.io/2012/09/17/crossfilter-tutorial/
var livingThings = crossfilter([
// Fact data.
{ name: “Rusty”, type: “human”, legs: 2 },
{ name: “Alex”, type: “human”, legs: 2 },
{ name: “Lassie”, type: “dog”, legs: 4 },
{ name: “Spot”, type: “dog”, legs: 4 },
{ name: “Polly”, type: “bird”, legs: 2 },
{ name: “Fiona”, type: “plant”, legs: 0 }
]);
For example, how many living things are in my house?
To do this, we’ll call the groupAll convenience function, which selects all
records into a single group, and then the reduceCount function, which
creates a count of the records.
// How many living things are in my house?
var n = livingThings.groupAll().reduceCount().value();
console.log("There are " + n + " living things in my house.") // 6
Now let’s get a count of all the legs in my house. Again, we’ll use the groupAll function to get all records in a single group, but then we call the
reduceSum function. This is going to sum values together. What values?
Well, we want legs, so let’s pass a function that extracts and returns the number of legs from the fact.
// How many total legs are in my house?
var legs = livingThings.groupAll().reduceSum(function(fact) {
return fact.legs;
}).value()
console.log("There are " + legs + " legs in my house.")
reduceCount function creates a count of the records.
reduceSum function is the sum values of these records.