I have an object with sales numbers and want to get return the name and sales of the highest seller, but I keep getting an error of cannot read property of undefined:
var salesTeam = [{name: {first: 'aleen', last: 'atkins'}, age: 26, sales: '$2314'},
{name: {first: 'alvaro', last: 'angelos'}, age: 55, sales: '$1668'},
{name: {first: 'denese', last: 'dossett'}, age: 29, sales: '$9248'},
{name: {first: 'douglas', last: 'denney'}, age: 53, sales: '$5058'},
{name: {first: 'earline', last: 'erickson'}, age: 19, sales: '$18876'},
{name: {first: 'herman', last: 'hazell'}, age: 25, sales: '$2746'},
{name: {first: 'homer', last: 'hirth'}, age: 26, sales: '$474'},
{name: {first: 'hwa', last: 'heidt'}, age: 53, sales: '$9607'},
{name: {first: 'hyon', last: 'hampshire'}, age: 46, sales: '$13598'},
{name: {first: 'issac', last: 'ingerson'}, age: 45, sales: '$5225'},
{name: {first: 'jeraldine', last: 'joplin'}, age: 39, sales: '$2891'},
{name: {first: 'jin', last: 'jeffrey'}, age: 17, sales: '$14402'},
{name: {first: 'joleen', last: 'jolin'}, age: 45, sales: '$15736'},
{name: {first: 'jude', last: 'jarrett'}, age: 53, sales: '$7557'},
{name: {first: 'magda', last: 'mireles'}, age: 18, sales: '$1498'},
{name: {first: 'mistie', last: 'montealegre'}, age: 31, sales: '$6920'},
{name: {first: 'nancy', last: 'napoli'}, age: 49, sales: '$5255'},
{name: {first: 'regine', last: 'rohrbaugh'}, age: 33, sales: '$7881'},
{name: {first: 'rolando', last: 'riebel'}, age: 35, sales: '$8573'},
{name: {first: 'scarlett', last: 'stagg'}, age: 36, sales: '$7126'},
{name: {first: 'sherron', last: 'strawn'}, age: 36, sales: '$8848'},
{name: {first: 'susan', last: 'shilling'}, age: 29, sales: '$8542'},
{name: {first: 'tama', last: 'tworek'}, age: 16, sales: '$9200'},
{name: {first: 'tonisha', last: 'taunton'}, age: 41, sales: '$5219'},
{name: {first: 'vergie', last: 'villescas'}, age: 25, sales: '$8712'}];
var highestEarner = function (companies) {
var ret = companies.reduce(function(acc,element,i){
if (parseInt(element['sales'].slice(1)) > acc['sales']){
acc['sales'] = element['sales'];
acc['name'] = element['name']['first'] +" "+ element['name']['last'];
}
},{sales: 0, name: ''});
return ret;
};
console.log(highestEarner(salesTeam));
You need to return the accumulator in each iteration, ie you are missing return acc after the if {...}. Also, you're assigning the currency-formatted value to acc['sales'] so you'll need to slice and parseInt that too (or just store the numeric value)...
const salesTeam = [{"name":{"first":"aleen","last":"atkins"},"age":26,"sales":"$2314"},{"name":{"first":"alvaro","last":"angelos"},"age":55,"sales":"$1668"},{"name":{"first":"denese","last":"dossett"},"age":29,"sales":"$9248"},{"name":{"first":"douglas","last":"denney"},"age":53,"sales":"$5058"},{"name":{"first":"earline","last":"erickson"},"age":19,"sales":"$18876"},{"name":{"first":"herman","last":"hazell"},"age":25,"sales":"$2746"},{"name":{"first":"homer","last":"hirth"},"age":26,"sales":"$474"},{"name":{"first":"hwa","last":"heidt"},"age":53,"sales":"$9607"},{"name":{"first":"hyon","last":"hampshire"},"age":46,"sales":"$13598"},{"name":{"first":"issac","last":"ingerson"},"age":45,"sales":"$5225"},{"name":{"first":"jeraldine","last":"joplin"},"age":39,"sales":"$2891"},{"name":{"first":"jin","last":"jeffrey"},"age":17,"sales":"$14402"},{"name":{"first":"joleen","last":"jolin"},"age":45,"sales":"$15736"},{"name":{"first":"jude","last":"jarrett"},"age":53,"sales":"$7557"},{"name":{"first":"magda","last":"mireles"},"age":18,"sales":"$1498"},{"name":{"first":"mistie","last":"montealegre"},"age":31,"sales":"$6920"},{"name":{"first":"nancy","last":"napoli"},"age":49,"sales":"$5255"},{"name":{"first":"regine","last":"rohrbaugh"},"age":33,"sales":"$7881"},{"name":{"first":"rolando","last":"riebel"},"age":35,"sales":"$8573"},{"name":{"first":"scarlett","last":"stagg"},"age":36,"sales":"$7126"},{"name":{"first":"sherron","last":"strawn"},"age":36,"sales":"$8848"},{"name":{"first":"susan","last":"shilling"},"age":29,"sales":"$8542"},{"name":{"first":"tama","last":"tworek"},"age":16,"sales":"$9200"},{"name":{"first":"tonisha","last":"taunton"},"age":41,"sales":"$5219"},{"name":{"first":"vergie","last":"villescas"},"age":25,"sales":"$8712"}];
var highestEarner = function (companies) {
var ret = companies.reduce(function(acc,element) {
let currentSales = parseInt(element.sales.slice(1))
if (currentSales > acc.sales) {
acc.sales = currentSales;
acc.name = `${element.name.first} ${element.name.last}`
}
return acc;
},{sales: 0, name: ''});
return ret;
};
console.log(highestEarner(salesTeam));
The simple rule while working with reducer is that, whatever data format you have in each element of the array, make sure you are returning the same format including all the elements in every run so that it can use the returned value as accumulator (acc) for the next run.
A simple mistake which I learned from below:
This fixed the issue.
Related
Hi guys and sorry for my english. I have this array of objects and I need to get an input like:
{name: Karen, age: 12} -> Karen-12.
How can I do it?
This is the exercise:
function nicknameMap(p) {
}
const p = [
{ name: 'ninny', age: 19},
{ name: 'albert', age: 20},
{ name: 'daniel', age: 60},
{ name: 'bob', age: 20},
{ name: 'wilfred', age: 40},
{ name: 'rob', age: 22},
{ name: 'gary', age: 9},
{ name: 'robin', age: 19},
{ name: 'carl', age: 43 },
{ name: 'v', age: 82 }
];
const nicknames = nicknameMap(p);
console.log(p);
console.log(nicknames);```
Use the .map() array method as follows:
function nicknameMap(p) {
return p.map(({name,age}) => `${name}-${age}`);
}
//output
//[
// "ninny-19",
// "albert-20",
// "daniel-60",
// "bob-20",
// .....
//]
function nicknameMap(p) {
return p.map(({name,age}) => `${name}-${age}`);
}
const p = [
{ name: 'ninny', age: 19},
{ name: 'albert', age: 20},
{ name: 'daniel', age: 60},
{ name: 'bob', age: 20},
{ name: 'wilfred', age: 40},
{ name: 'rob', age: 22},
{ name: 'gary', age: 9},
{ name: 'robin', age: 19},
{ name: 'carl', age: 43 },
{ name: 'v', age: 82 }
];
const nicknames = nicknameMap(p);
console.log(p);
console.log(nicknames);
function nicknameMap(p) {
let result = Array();
p.forEach((n) => {
result.push(`${n.name}-${n.age}`);
});
return result;
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push
It's best to learn by yourself, but I'm assuming you've had a crack at it and are asking because you have run out of options.
EDIT: amlxv solution is a more "Javascript" way of doing it, and is technically more correct than mine.
Below is a solution to your problem.
function nicknameMap(p) {
let arr = [];
for(let i = 0; i<p.length; i++){
arr.push(p[i].name + "-" + p[i].age);
}
return arr;
}
const p = [
{ name: 'ninny', age: 19},
{ name: 'albert', age: 20},
{ name: 'daniel', age: 60},
{ name: 'bob', age: 20},
{ name: 'wilfred', age: 40},
{ name: 'rob', age: 22},
{ name: 'gary', age: 9},
{ name: 'robin', age: 19},
{ name: 'carl', age: 43 },
{ name: 'v', age: 82 }
];
const nicknames = nicknameMap(p);
console.log(p);
console.log(nicknames);
I am attempting to check whether all age groups from teen to centenarian are represented in an array.
My logic path has been:
Create an array with pre-defined decade-based age brackets [1, 2, 3, ... , 10]
Isolate the age value of each element in the sample array of objects
Divide those ages by 10 to get what decade the age falls in
parseInt that number to get an integer and put resultant figures in new array
Compare that array with the pre-defined age bracket array created initially.
The expected output is true but I am instead getting false.
Another logic issue I am facing is that the oldest age in the sample array, 128, reduces to 12 after dividing/parsing whereas it would be preferable for it to check if the int is > 10 instead of specifically 10.
Code below:
const devAges = list.map((list) => {
return list.age
})
const devAgesDiv = devAges.map(i => i / 10);
for(i = 0; i < devAgesDiv.length; i++){
devAgesDiv[i] = parseInt(devAgesDiv[i]);
}
function allAges(list) {
const ageBrackets = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
return ageBrackets.every((ageBracket) =>
list.some((listItem) => listItem.ageBracket === ageBracket)
);
}
console.log(allAges(list)); // output false;
Sample array below:
var list = [
{ firstName: 'Harry', lastName: 'K.', country: 'Brazil', continent: 'Americas', age: 19, language: 'Python' },
{ firstName: 'Kseniya', lastName: 'T.', country: 'Belarus', continent: 'Europe', age: 29, language: 'JavaScript' },
{ firstName: 'Jing', lastName: 'X.', country: 'China', continent: 'Asia', age: 39, language: 'Ruby' },
{ firstName: 'Noa', lastName: 'A.', country: 'Israel', continent: 'Asia', age: 40, language: 'Ruby' },
{ firstName: 'Andrei', lastName: 'E.', country: 'Romania', continent: 'Europe', age: 59, language: 'C' },
{ firstName: 'Maria', lastName: 'S.', country: 'Peru', continent: 'Americas', age: 60, language: 'C' },
{ firstName: 'Lukas', lastName: 'X.', country: 'Croatia', continent: 'Europe', age: 75, language: 'Python' },
{ firstName: 'Chloe', lastName: 'K.', country: 'Guernsey', continent: 'Europe', age: 88, language: 'Ruby' },
{ firstName: 'Viktoria', lastName: 'W.', country: 'Bulgaria', continent: 'Europe', age: 98, language: 'PHP' },
{ firstName: 'Piotr', lastName: 'B.', country: 'Poland', continent: 'Europe', age: 128, language: 'JavaScript' }
];
You can make two updates to get the desired result:
devAgesDiv - check if the list age is over 100 and return 10 otherwise divide by 10; you can parseInt the result of that test
You can use includes in allAges to check every ageBracket is represented
See below:
const list = [
{ firstName: 'Harry', lastName: 'K.', country: 'Brazil', continent: 'Americas', age: 19, language: 'Python' },
{ firstName: 'Kseniya', lastName: 'T.', country: 'Belarus', continent: 'Europe', age: 29, language: 'JavaScript' },
{ firstName: 'Jing', lastName: 'X.', country: 'China', continent: 'Asia', age: 39, language: 'Ruby' },
{ firstName: 'Noa', lastName: 'A.', country: 'Israel', continent: 'Asia', age: 40, language: 'Ruby' },
{ firstName: 'Andrei', lastName: 'E.', country: 'Romania', continent: 'Europe', age: 59, language: 'C' },
{ firstName: 'Maria', lastName: 'S.', country: 'Peru', continent: 'Americas', age: 60, language: 'C' },
{ firstName: 'Lukas', lastName: 'X.', country: 'Croatia', continent: 'Europe', age: 75, language: 'Python' },
{ firstName: 'Chloe', lastName: 'K.', country: 'Guernsey', continent: 'Europe', age: 88, language: 'Ruby' },
{ firstName: 'Viktoria', lastName: 'W.', country: 'Bulgaria', continent: 'Europe', age: 98, language: 'PHP' },
{ firstName: 'Piotr', lastName: 'B.', country: 'Poland', continent: 'Europe', age: 128, language: 'JavaScript' }
];
const devAgesDiv = list.map(item => parseInt(item.age > 100 ? 10 : item.age / 10));
const ageBrackets = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
function allAges(list) {
return ageBrackets.every(ageBracket => list.includes(ageBracket));
}
console.log(allAges(devAgesDiv)); // true
I'm using React for my application and I've put my data (objects) into an array. Is there a way to output my data (array of objects) that loads all at once (such as Twitter, Instagram, Facebook)?
Currently I'm using a for loop where it loads one by one from my latest post to the end.
Here's a sample for loop to demonstrate.
var myArray = [
{name: 'Dwayne', age: 28},
{name: 'Rob', age: 32},
{name: 'Marie', age: 22},
{name: 'Sarah', age: 40},
{name: 'Emma', age: 29},
{name: 'James', age: 30}
];
for (var i = myArray.length - 1; i >= 0; i--){
console.log(myArray[i].name, myArray[i].age);
}
Here's an example of using map to generate a <p/> element with name and age inside it.
render(){
const myArray = [
{name: 'Dwayne', age: 28},
{name: 'Rob', age: 32},
{name: 'Marie', age: 22},
{name: 'Sarah', age: 40},
{name: 'Emma', age: 29},
{name: 'James', age: 30}
];
return(
<div>
{myArray.map((item, index) => (
<p key={`${item.name}-${index}`}>
Name:{item.name}, Age:{item.age}
</p>
))}
</div>
)
}
The above code would output
<div>
<p>Name:Dwayne, Age:28</p>
<p>Name:Rob, Age:32</p>
<p>Name:Marie, Age:22</p>
<p>Name:Sarah, Age:40</p>
<p>Name:Emma, Age:29</p>
<p>Name:James, Age:30</p>
</div>
Say you have csv data file like this:
name, age
Bob, 27
George, 25
Bill, 22
Henry,27
Carol,25
Mary, 28
Harold,27
Jane, 25
I want to aggregate totals by age for a bar chart. So that I get totals like this: age 27(3), age 25(2), etc.
I am using d3 v4
As mentioned in the comments, you could use d3.nest:
const data = [
{name: 'Bob', age: 27},
{name: 'George', age: 25},
{name: 'Bill', age: 2},
{name: 'Henry', age: 27},
{name: 'Carol', age: 25},
{name: 'Mary', age: 28},
{name: 'Harold', age: 27},
{name: 'Jane', age: 25},
];
console.log(d3.nest()
.key(d => d.age)
.rollup(results => results.length)
.entries(data));
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.min.js"></script>
I have an array, to simplify lets say persons with first, last, and age. I want to make a new array of all persons that have the same first name, same last name and same age. For example my starting array:
[
{id: 1, first: 'fred', last: 'smith', age: 21},
{id: 2, first: 'fred', last: 'smith', age: 21},
{id: 3, first: 'tom', last: 'smith', age: 21},
{id: 4, first: 'fred', last: 'smith', age: 32}
]
I would like to return the duplicates that match first/last/age:
[
{id: 1, first: 'fred', last: 'smith', age: 21},
{id: 2, first: 'fred', last: 'smith', age: 21}
]
I'm struggling with _.uniq to figure out how to do this, any help is appreciated.
You can make use of _.groupBy() to group values, make sure that it is grouped by values that you determine to be the criteria for a duplicate. You can then _.filter() each grouped values by the lengths of the arrays they accumulated and then _.flatten() it to obtain the final array.
var data = [
{id: 1, first: 'fred', last: 'smith', age: 21},
{id: 2, first: 'fred', last: 'smith', age: 21},
{id: 3, first: 'tom', last: 'smith', age: 21},
{id: 4, first: 'fred', last: 'smith', age: 32}
];
var result = _(data)
.groupBy(i => _(i).pick('first', 'last', 'age').values().value())
.filter(i => i.length > 1)
.flatten()
.value();
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.11.2/lodash.js"></script>