Reputation: 55
I am trying to combine two separate functions into a single function that can push a new item into one of two available arrays, depending on what the input is (in my situation, addToProsList or addToConsList).
Here is my current code. Having issues turning it into a single function (addToList()), because I'm not sure how I would be able to indicate which array it would enter with just the 'detail' parameter. I'm assuming I would need an if/else statement. I know this is simple, I am very stuck on how to approach this.
var housePros = ['3 bed', '2 bath'];
var houseCons = ['over budget'];
function addToProsList(detail) {
housePros.push(detail);
console.log('Updated List: ', housePros);
}
function addToConsList(detail) {
houseCons.push(detail);
console.log('Updated List: ', houseCons);
}
addToProsList('big yard');
addToConsList('no garage');
function addToList(detail) {}
Upvotes: 0
Views: 61
Reputation: 21
let housePros = ['3 bed', '2 bath'];
let houseCons = ['over budget'];
// changing the addToList variable as you can pass the array
// in which you are adding the new elementelement
function addToList(detail, addList){
addList.push(detail);
addList.forEach(elem => console.log(elem));
console.log("\n");
}
addToList('big yard', housePros);
addToList('no garage', houseCons);
Upvotes: 0
Reputation: 29042
You can use a second argument that indicates whether it's a pro or con:
function addToList (detail, isPro) {
(isPro ? housePros : houseCons).push(detail)
}
addToList('big yard', true)
addToList('no garage', false)
...or you could use an object with multiple lists:
const houseAttribs = { pro: [], con: [] }
function addToList (attrib, detail) {
houseAttrib[attrib].push(detail)
}
addToList('pro', 'big yard')
addToList('con', 'no garage')
Upvotes: 0
Reputation: 28206
This could be what you are looking for:
var housePros = ['3 bed', '2 bath'];
var houseCons = ['over budget'];
function addToList(detail,cons) {
// "first shot":
// const list=window["house"+(cons?"Cons":"Pros")];
// alternative (better) solution:
const list=cons?houseCons:housePros;
list.push(detail);
console.log('Updated List: ', list);
}
addToList('big yard');
addToList('no garage',1);
The second argument of addToList()
determines whether the item is to be pushed onto housePros
(default) or houseCons
(whenever the value cons
is "truthy").
Upvotes: 1
Reputation: 202
I think it will help you:
var housePros = ['3 bed', '2 bath'];
var houseCons = ['over budget'];
function addToList(detail, arr) {
arr.push(detail);
console.log('Updated List: ', arr);
}
addToList('big yard', housePros);
addToList('no garage', houseCons);
Upvotes: 0