Solve a programming problem with array methods? - javascript

I am having difficulties solving the following programming problem:
Write a function that keeps track of guests that are going
to a house party. You will be given an array of strings. Each string
will be one of the following:
{name} is going!
{name} is not going!
If you receive the first type of input, you have to add the person if
he/she is not in the list (If he/she is in the list print: {name} is
already in the list! If you receive the second type of input, you have
to remove the person if he/she is in the list (if not, print:{name} is
not in the list!).
At the end print all the guests each on a separate line.
The assignment is to solve it with array methods, for loops, for each, for of…anything that works.
I know it might be too simple for this website and I’m sorry but I have been struggling with it for too many hours and unfortunately this is as far as I can go with the code… My problem is that I can't seem to divide it into small steps and execute them with array methods and loops...
function houseParty(input) {
let guestsList = [];
let notComing = [];
for (let i = 0; i < input.length; i++) {
if (input[i].includes('not')) {
notComing.push(input[i]);
} else {
guestsList.push(input[i]);
}
}
}
houseParty(['Allie is going!',
'George is going!',
'John is not going!',
'George is not going!'
])
This is an example of an input:
[Tom is going!,
Annie is going!,
Tom is going!,
Garry is going!,
Jerry is going!]
And this is the expected output:
Tom is already in the list!
Tom
Annie
Garry
Jerry
I would be very happy if you could explain to me the logic behind the programming problem and how you guys 'translate' it into small steps so that the program does what needs to be done.

Your question is about the puzzle's logic and how to form steps to solve it. The ability to form the steps necessary is more of a way of thinking than anything else, it comes with practice. As for the logic, the solution can be implemented as follows:
create a collection (ie: array) of names that are going to the party
iterate over the input array
extrapolate from the message both the name of the person and if they are going or not.
if they are going and their name is not in the collection add their name to the collection
if they are not going and the name is in the collection then make sure their name is removed
after collecting your guests, iterate over your finalized collection and log your guests names to the console

**Are you looking this?**Please follow the explanation from the #foobar2k19's answer.
function houseParty(input) {
let guestsList = [];
for (let i = 0; i < input.length; i++) {
let nameOfThePerson = input[i].split(" ")[0];
if (input[i].includes('not')) {
if (guestsList.indexOf(nameOfThePerson) > -1) {
guestsList.splice(guestsList.indexOf(nameOfThePerson), 1);
}
} else if(guestsList.includes(nameOfThePerson)) {
guestsList.push(nameOfThePerson + ' is already in the list!');
} else {
guestsList.push(nameOfThePerson);
}
}
return guestsList;
}
const inputArr = ['Tom is going!',
'Annie is going!',
'Tom is going!',
'Garry is going!',
'Jerry is going!'];
console.log(houseParty(inputArr));

Try using Array#prototype#reduce to build a frequency list first, then mapping it to the response you want.
function houseParty(input) {
const res = Object.entries(input.reduce((acc, curr) => {
const name = curr.split(' ')[0];
if (!acc[name]) {
acc[name] = 1;
} else {
acc[name] += 1;
}
return acc;
}, {}))
.map(x => {
if (x[1] > 1) {
return `${x[0]} is already in the list`;
} else {
return x[0];
}
});
return res;
}
const result = houseParty(['Allie is going!',
'George is going!',
'John is not going!',
'George is not going!'
]);
console.log(result);

I'll give you more 'easy to understand' way.
Note 1:
better to check 'not going' match in string, because of the name may
contain 'not' - there are a lot of strange names around the world (For
example Knott).
Note 2:
You have to remove a person from the list if his/her name repeated in
input with different status.
function houseParty(input) {
let guestList = [];
let notComing = [];
let name, going;
//loop through input
for(let i = 0; i < input.length; i++) {
//get persons name
name = input[i].split(' ')[0];
//set going status
going = !input[i].includes('not going');
if (going) {
//check name in going list
if (guestList.indexOf(name) > -1) {
//this person is already in list
console.log(`${name} is in the list`);
}
else {
//add person in list
guestList.push(name);
}
//check if person was in not going list, remove from it
if (notComing.indexOf(name) > -1) {
//remove from not going list
notComing.splice(notComing.indexOf(name), 1);
}
}
else {
//check if name is in not going list
if (notComing.indexOf(name) > -1) {
console.log(`${name} is in the list`);
}
else {
notComing.push(name);
}
//check if person was in going list before
if (guestList.indexOf(name) > -1) {
guestList.splice(guestList.indexOf(name), 1);
}
}
}
//you have both lists filled now
console.log("Guests: ", guestList);
console.log("Not coming: ", notComing);
}
let input = [
'Allie is going!',
'George is going!',
'John is not going!',
'George is going!',
'George is not going!',
'Knott is going!'
];
//test
houseParty(input);

Related

How to filter a JS array based on user input in such a way that user writes "Brl", and it shows Berlin (letters aren't one after another immediately)?

I have an array of cities
var cities = ['Berlin', 'Bucharest', 'Paris', 'Munich', 'Amsterdam', 'Milan'];
This array needs to be filtered based on the search input passed (f.e., user inputs 'm', and it shows 'Munich', 'Amsterdam', and 'Milan', then the user adds 'a' to 'm' in search input (writes 'ma'), and it shows him "Amsterdam' and 'Milan', although these letters are not one immediately after another). Moreover, I then need these letters to be highlighted in some way, so, let's say, letters 'm' & 'a' in these words are yellow.
This is what I've done so far, but it doesn't work as I need.
var input = document.querySelector("input").value.toLowerCase().trim();
document.addEventListener('input', search)
function search() {
var filteredArray = cities.filter(x => x.toLowerCase().includes(input));
console.log(filteredArray);//to see what I've got
}
Appreciate any help! I'm new to JavaScript. Thanks!
You might filter like this.
document.addEventListener('input', search);
const cities = ['Berlin', 'Bucharest', 'Paris', 'Munich', 'Amsterdam', 'Milan'];
function search(e) {
const input = e.target.value.toLowerCase().trim();
const filteredArray = cities.filter(x => {
const c = x.toLowerCase();
let m = 0;
for (let l of input) {
const i = c.substr(m).indexOf(l);
if (i < m) return false;
m = i;
}
return true;
});
console.log(filteredArray);//to see what I've got
}
<input>
Also, you might remember indexes to highlight matching letters.

How to access elements inside an array of objects in Javascript for a movieapp prototype

I've only shown the JS part of my code because the .html part only has one input box with name="my-input" inside a form.
What happens in this function is, if I enter 'Adventure' in my input box it gives me Edge of Tomorrow as the title of the movie and if I enter Romantic it gives me Lalaland likewise. Now what I want is, shown in the movieList1() function i.e. I have two objects with same genre 'Adventure' for example, then I would want both the movie title, 'Edge of Tomorrow' and 'Dark Force' to be shown in my empty list with id 'here'. I want title of all the movies to be shown if the genre is similar but I'm able to only get one movie title at a time that is shown. I'm new to JS and object and array of objects looks a little confusing. Any help would be very much appreciated.
function movieList(){
//This function is called in an 'onkeyup' event inside the input box.
var x = document.forms["my-form"]["my-input"].value; // x has what the user enters inside the
inputbox.
const objList = [{
title:'Edge of Tommorow',
Genre: 'Adventure',
},
{
title:'DarkForce',
Genre: 'Tactical',
},
{
title:'LalaLand',
Genre:'Romantic'
}];
objList.forEach((ele,index) => {
if(ele.Genre=='Adventure' && x==ele.Genre) {
var ans = ele.title;
document.getElementById('here').innerHTML = ans; // 'here' has the id of an empty <li></li> where
the title is shown.
}
else if(ele.Genre=='Tactical' && x==ele.Genre)
{
var ans = ele.title;
document.getElementById('here').innerHTML = ans;
}
else if(ele.Genre=='Romantic' && x==ele.Genre)
{
var ans = ele.title;
document.getElementById('here').innerHTML = ans;
}
else if(x=='')
{
document.getElementById('here').innerHTML='';
}
});
}
function movieList1(){
//This function is called in an 'onkeyup' event inside the input box.
var x = document.forms["my-form"]["my-input"].value; // x has what the user enters inside the input
box.
const objList = [{
title:'Edge of Tommorow',
Genre: 'Adventure',
},
{
title:'DarkForce',
Genre: 'Tactical, Adventure',
},
{
title:'LalaLand',
Genre:'Romantic,Tactical'
}];
objList.forEach((ele,index) => {
if(ele.Genre=='Adventure' && x==ele.Genre) {
var ans = ele.title;
document.getElementById('here').innerHTML = ans; // 'here' has the id of an empty <li></li> where
the title is shown.
}
else if(ele.Genre=='Tactical' && x==ele.Genre)
{
var ans = ele.title;
document.getElementById('here').innerHTML = ans;
}
else if(ele.Genre=='Romantic' && x==ele.Genre)
{
var ans = ele.title;
document.getElementById('here').innerHTML = ans;
}
else if(x=='')
{
document.getElementById('here').innerHTML='';
}
});
}
I'm guessing this is what you want to do.
const objList = [{
title: 'Edge of Tommorow',
Genre: 'Adventure',
},
{
title: 'DarkForce',
Genre: 'Tactical',
},
{
title: 'LalaLand',
Genre: 'Adventure'
}];
let Gen = "Adventure"; // suppose this is from your input
let temp = []; // create an array to store all similar genre title
objList.forEach(x => {
if (x.Genre == Gen) {
temp.push(x.title);
}
})
console.log(temp);
Output:
[ 'Edge of Tommorow', 'LalaLand' ]
you can also store objects in the temp array.
Thinking you are expecting the output like:: (Method movieList1)
for inputGenre=Tactical output will be DarkForce,LalaLand
for inputGenre=Adventure output will be Edge of Tommorow,DarkForce
document.getElementById("txtGenre").addEventListener("keyup",searchMovies)
function searchMovies(){
let inputGenre=document.getElementById("txtGenre").value;
const objList = [{
title:'Edge of Tommorow',
Genre: 'Adventure',
},
{
title:'DarkForce',
Genre: 'Tactical, Adventure',
},
{
title:'LalaLand',
Genre:'Romantic,Tactical'
}];
let filterdData =objList.filter(r=>r.Genre.includes(inputGenre));
console.log(filterdData);
document.getElementById("result").innerHTML=filterdData.map(r=>r.Genre).join(",");
}
#result{
background-color:green;
}
Genre input: <input type="text" id="txtGenre" onClick="searchMovies"/>
<br/>
Output Movies List:
<div id="result">
</div>
There reason you are getting only one movie name is, you are re-writing the HTML again with the latest movie that matched the criteria each time forEach runs. You need to adjust your variables and how you assign your result to HTML.
Lets keep ans out of the loop, so it doesn't get overwrittern. And write to html at the end, after you have filtered all per your input.
var ans = [];
objList.forEach((ele,index) => {
if(ele.Genre=='Adventure' && x==ele.Genre) {
ans.push(ele.title);
} else if(ele.Genre=='Tactical' && x==ele.Genre) {
ans.push(ele.title);
} else if(ele.Genre=='Romantic' && x==ele.Genre) {
ans.push(ele.title);
}
// We dont need this
// else if(x=='') {
// document.getElementById('here').innerHTML='';
// }
});
document.getElementById('here').innerHTML = ans.join(', ');
At last, you join the answer using the in-built array function.
Now if you notice, your if statements are pretty much the same except for the hardcoded genre. So you could further refactor it.
var ans = [];
var genre = 'Adventure'; // assign your genre from input box here.
objList.forEach((ele,index) => {
if (ele.Genre == genre && x==ele.Genre) {
ans.push(ele.title);
}
});
document.getElementById('here').innerHTML = ans.join(', ');
Now you would have a single if statement which is easy to understand and modify.

Preventing duplicate objects from being added to array?

I am building a little shop for a client and storing the information as an array of objects. But I want to ensure that I am not creating "duplicate" objects. I have seen similar solutions, but perhaps it is my "newness" to coding preventing me from getting the gist of them to implement in my own code, so I'd like some advice specific to what I have done.
I have tried putting my code in an if look, and if no "part", my variable looking for part number, exists in the code, then add the part, and could not get it to function.
Here is the function I am working on:
function submitButton(something) {
window.scroll(0, 0);
cartData = ($(this).attr("data").split(','));
arrObj.push({
part: cartData[0],
description: cartData[1]
});
}
arrObj is defined as a global variable, and is what I am working with here, with a "part" and a "description", which is the data I am trying to save from elsewhere and output to my "#cart". I have that part working, I just want to ensure that the user cannot add the same item twice. (or more times.)
Sorry if my code is shoddy or I look ignorant; I am currently a student trying to figure these things out so most of JS and Jquery is completely new to me. Thank you.
You can create a proxy and use Map to hold and access values, something like this
let cart = new Map([{ id: 1, title: "Dog toy" }, { id: 2, title: "Best of Stackoverflow 2018" }].map(v=>[v.id,v]));
let handler = {
set: function(target,prop, value, reciver){
if(target.has(+prop)){
console.log('already available')
} else{
target.set(prop,value)
}
},
get: function(target,prop){
return target.get(prop)
}
}
let proxied = new Proxy(cart, handler)
proxied['1'] = {id:1,title:'Dog toy'}
proxied['3'] = {id:3,title:'Dog toy new value'}
console.log(proxied['3'])
Assuming the 'part' property is unique on every cartData, I did checking only based on it.
function submitButton(something) {
window.scroll(0, 0);
cartData = ($(this).attr("data").split(','));
if(!isDuplicate(cartData))
arrObj.push({
part: cartData[0],
description: cartData[1]
});
}
const isDuplicate = (arr) => {
for(obj of arrObj){
if(arr[0] === obj.part)
return true;
}
return false;
}
If you want to do the checking on both 'part' and 'description' properties, you may replace the if statement with if(arr[0] === obj.part && arr[1] === obj.description).
Thanks everyone for their suggestions. Using this and help from a friend, this is the solution that worked:
function submitButton(something) {
window.scroll(0,0);
cartData = ($(this).attr("data").split(','));
let cartObj = {
part: cartData[0],
description: cartData[1],
quantity: 1
}
match = false
arrObj.forEach(function(cartObject){
if (cartObject.part == cartData[0]) {
match = true;
}
})
console.log(arrObj);
if (!match) {
arrObj.push(cartObj);
}
Okay, you have multiple possible approaches to this. All of them need you to specify some kind of identifier on the items which the user can add. Usually, this is just an ID integer.
So, if you have that integer you can do the following check to make sure it's not in the array of objects:
let cart = [{ id: 1, title: "Dog toy" }, { id: 2, title: "Best of Stackoverflow 2018" }];
function isInCart(id) {
return cart.some(obj => obj.id === id);
}
console.log(isInCart(1));
console.log(isInCart(3));
Another approach is saving the items by their id in an object:
let cart = { 1: { title: "Dog toy" }, 2: { title: "Best of Stackoverflow 2018" } };
function isInCart(id) {
if(cart[id]) return true;
return false;
}
Try to use indexOf to check if the object exists, for example:
var beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];
console.log(beasts.indexOf('aaa'));
// expected output: -1

Recursively process JSON array to find common values across all object in array

I have been very much struggling to recursively process this JSON structure over the last few days and am hoping someone can assist me.
I have an array which contains multiple JSON objects. Each object represents a question and has 1 or more possible answers. Each answer contains 1 or more possible conditions which in turn contain 1 datapoint and 1 requiredValue.
JSON object
[
{
"originalQ": "Have you been to hospital?",
"originalA": "No",
"potentialAnswers": [
{
"conditions": [
{
"datapoint": "Hospitalization",
"assoicatedValue": "more than 2 years ago "
}
]
},
{
"conditions": [
{
"datapoint": "Hospitalization",
"assoicatedValue": "never"
}
]
}
]
},
{
"originalQ": "Has a medical professional diagnosed you?",
"originalA": "No",
"potentialAnswers": [
{
"conditions": [
{
"datapoint": "OtherDiagnosis",
"assoicatedValue": "has never"
},
{
"datapoint": "Hospitalization",
"assoicatedValue": "never"
}
]
}
]
},
{
"originalQ": "Are you taking medication?",
"originalA": "Yes",
"potentialAnswers": [
{
"conditions": [
{
"datapoint": "Medications",
"assoicatedValue": "1-3"
}
]
},
{
"conditions": [
{
"datapoint": "Medications",
"assoicatedValue": "4 or more"
}
]
}
]
},
{
"originalQ": "How many different medications do you take?",
"originalA": "4 or more",
"potentialAnswers": [
{
"conditions": [
{
"datapoint": "Medications",
"assoicatedValue": "4 or more"
}
]
}
]
}
]
I need to get a JSON object that contains datapoint:assoicatedValue pairs that would allow us to find one matching element in each question potentialAnswer array for each question object.
There will always be fewer datapoints than answers so I need to know what value I can assign each datapoint in order to have 1 valid object in the potentialAnswer array for each question. If there are no such possible combination I need to be alerted to that.
Ultimately each datapoint can only have one value so whatever values they are assigned cannot conflict with the answers for other questions. This would be considered an overall object answer.
Some addition info:
Every is dynamically generated i.e. datapoint names can change between runs (but consistent across objects for same run), number of question objects changes.
There are some cases where it will not be possible to find datapoint values and it such cases the function should return that info.
Outcome below matches at least one potential answer in each question.
Required Outcome
{
"Hospitalization": "never ",
"OtherDiagnosis": "has never",
"Medications": "4 or more"
}
I have tried a number of approaches to this but always run into an issue I cannot solve. The code below is the closest I've gotten. It works in most cases but seems to have issues if it encounters an issue in the last question object.
Code Attempt
let allQuestionData = require('./datafile.1.json');
findCorrectAnswerCombination(allQuestionData);
function findCorrectAnswerCombination(allQuestionData) {
console.log(ProcessNextQuestion(allQuestionData));
}
//This function will run all of the next questions
function ProcessNextQuestion(allQuestions, startingIndex = 0, dpObj = {}, questionNum = 1) {
try{
//create deep copy of Obj
let copyDpObj = JSON.parse(JSON.stringify(dpObj))
//Loop through all of the remaining questions
for (let i = startingIndex; i < allQuestions.length; i++) {
let question = allQuestions[i];
for (let answerNum = 0; answerNum < question.potentialAnswers.length; answerNum++) {
let answer = question.potentialAnswers[answerNum];
//Determine if the current potential answer fits with the values already in the dpObj
if (doesAnswerFitInCurrentDPObject(answer, copyDpObj)) {
//Add the new datapoints to the doObj if there are any new dps
let tempDPObj = addValuesToDpObj(answer, dpObj);
//if this is the final question then we have a valid path
if (questionNum === allQuestions.length) {
return tempDPObj;
} else {
//recurively run on remaining questions
return ProcessNextQuestion(allQuestions, i + 1, tempDPObj, questionNum + 1);
}
}
}
}
return 'No matching values found'
}catch(err){
throw new Error(err)
}
}
function doesAnswerFitInCurrentDPObject(answer, dpObj) {
for (const condition of answer.conditions) {
if (dpObj.hasOwnProperty(condition.datapoint) && dpObj[condition.datapoint] !== condition.assoicatedValue) {
return false;
}
}
return true;
}
function addValuesToDpObj(answer, currentDpObj) {
let copyObj = JSON.parse(JSON.stringify(currentDpObj));
for (const condition of answer.conditions) {
copyObj[condition.datapoint] = condition.assoicatedValue;
}
return copyObj;
}
I eventually ended up finding the solution I was looking for, after much banging my head against the wall.
I was not handling the returning of values correctly. I needed to check after the recursion was called if the correct value was found. If it was I needed another return statement to end that loop. My loops would exist all the way back to the beginning in this case. Originally it would return regardless of whether or not the value was found.
//This function will run all of the next questions
function ProcessNextQuestion(allQuestions, startingIndex = 0, dpObj = {}, questionNum = 1) {
try {
//create deep copy of Obj
let copyDpObj = JSON.parse(JSON.stringify(dpObj))
//Loop through all of the remaining questions
for (let i = startingIndex; i < allQuestions.length; i++) {
let question = allQuestions[i];
for (let answerNum = 0; answerNum < question.potentialAnswers.length; answerNum++) {
let answer = question.potentialAnswers[answerNum];
//Determine if the current potential answer fits with the values already in the dpObj
if (doesAnswerFitInCurrentDPObject(answer, copyDpObj)) {
//Add the new datapoints to the doObj if there are any new dps
let tempDPObj = addValuesToDpObj(answer, dpObj);
//if this is the final question then we have a valid path
if (questionNum === allQuestions.length) {
return tempDPObj;
} else {
//******************
// This is what I needed to add
//******************
//recurively run on remaining questions
let processingResultFound = ProcessNextQuestion(allQuestions, i + 1, tempDPObj, questionNum + 1);
if (processingResultFound !== 'No matching values found') {
return processingResultFound;
}
//******************
}
}
}
}
return 'No matching values found'
} catch (err) {
throw new Error(err)
}
}

How to find the position of all array items from a loop

I'm brand new to programming so I apologize if this is a simple question.
I had a unique practice problem that I'm not quite sure how to solve:
I'm dealing with two arrays, both arrays are pulled from HTML elements on the page, one array is representing a bunch of states, and the next array is representing their populations. The point of the problem is to print the name of the states and their less than average populations.
To find and print all of the populations that are less than the average I used this code:
function code6() {
// clears screen.
clr();
// both variables pull data from HTML elements with functions.
var pop = getData2();
var states = getData();
var sum = 0;
for( var i = 0; i < pop.length; i++ ){
sum += parseInt( pop[i], 10 );
var avg = sum/pop.length;
if (pop[i] < avg) {
println(pop[i]);
// other functions used in the code to get data, print, and clear the screen.
function getData() {
var dataSource = getElement("states");
var numberArray = dataSource.value.split('\n');
// Nothing to split returns ['']
if (numberArray[0].length > 0) {
return(numberArray);
} else {
return [];
}
}
// Get the data from second data column
function getData2() {
var dataSource = getElement("pops");
var numberArray = dataSource.value.split('\n');
// Nothing to split returns ['']
if (numberArray[0].length > 0) {
return(numberArray);
} else {
return [];
}
}
// Clear the 'output' text area
function clr() {
var out = getElement("output");
out.value = "";
}
// Print to the 'output' HTML element and ADDS the line break
function println(x) {
if (arguments.length === 0) x = '';
print(x + '\n');
}
Now I just need to know how to get the value of these positions within the array so I can pull out the same positions from my states array and display them both side by side. Both arrays have the identical amount of items.
I hope this makes sense and thanks in advance to anyone who has time to take a look at this.
Best regards,
-E
Its a little hard to tell what you are trying to accomplish, but I guess you are going for something like:
'use strict'
function code6() {
const populations = ['39000000', '28000000', '21000000'];
const stateNames = ['california', 'texas', 'florida'];
const states = populations.map((population, i) => ({
'name': stateNames[i],
'population': Number(population),
}));
const sum = states.reduce((sum, state) => sum + state.population, 0);
const average = sum / populations.length;
states
.filter(state => state.population < average)
.forEach(state => {
const name = state.name;
const population = state.population;
console.log(`state name: ${name}, population: ${population}`);
});
}
// run the code
code6();
// state name: texas, population: 28000000
// state name: florida, population: 21000000
I took the liberty of refactoring your code to be a little more modern (es6) and Idiomatic. I hope its not to confusing for you. Feel free to ask any questions about it.
In short you should use:
'use strict' at the top of your files
const/let
use map/filter/forEach/reduce to iterate lists.
use meaningfull names
, and you should avoid:
classic indexed for-loop
parseInt
, and pretty much never ever use:
var
If your states array is built with corresponding indices to your pop one, like this:
states; //=> ['Alabama', 'Alaska', 'Arizona', ...]
pop; //=> [4863300, 741894, 6931071, ...]
then you could simply update your print statement to take that into account:
if (pop[i] < avg) {
println(state[i] + ': ' + pop[i]);
}
Or some such.
However, working with shared indices can be a very fragile way to use data. Could you rethink your getData and getData2 functions and combine them into one that returns a structure more like this the following?
states; //=> [
// {name: 'Alabama', pop: 4863300}
// {name: 'Alaska', pop: 741894},
// {name: 'Arizona', pop: 6931071},
// ...]
This would entail changes to the code above to work with the pop property of these objects, but it's probably more robust.
If your pop and state looks like:
var state = ['state1', 'state2', ...];
var pop = ['state1 pop', 'state2 pop', ...];
Then first of all, avg is already wrong. sum's value is running along with the loop turning avg's formula into sum as of iteration / array length instead of sum of all pops / array length. You should calculate the average beforehand. array.reduce will be your friend.
var average = pop.reduce(function(sum, val){return sum + val;}, 0) / pop.length;
Now for your filter operation, you can:
Zip up both arrays to one array using array.map.
Filter the resulting array with array.filter.
Finally, loop through the resulting array using array.forEach
Here's sample code:
var states = ['Alabama', 'Alaska'];
var pop = [4863300, 741894];
var average = pop.reduce(function(sum, val){return sum + val;}) / pop.length;
console.log('Average: ' + average);
states.map(function(state, index) {
// Convert 2 arrays to an array of objects representing state info
return { name: state, population: pop[index] };
}).filter(function(stateInfo) {
console.log(stateInfo);
// Filter each item by returning true on items you want to include
return stateInfo.population < average;
}).forEach(function(stateInfo) {
// Lastly, loop through your results
console.log(stateInfo.name + ' has ' + stateInfo.population + ' people');
});

Categories

Resources