Reputation: 21
I'm trying to double each element in an array
let arr = ['onions', 'tomatoes', 'etc'...';
with a for loop and keep getting NaN
error... I'm still learning so any advice would be appreciated.
I've tried for loop, .map()
, and other methods, but just can't see the obvious problem...
let newIngr = tortSoup.filter(function(value, index, arr) {
if (value !== 'onion' && value !== 'red pepper') {
return value;
console.log(newIngr);
});
}
let myReci = [];
for(var i = 0; i < newIngr.length; i++) {
myReci[i] = newIngr[i] * 2;
}
console.log(myReci);
Expected: each array element multiped by two and returned:
['onions', tomatoes', 'garlic', 'fontina']
would become:
['onions', 'onions', 'tomoatoes', 'tomatoes', garlic, 'garlic', 'fontina', 'fontina']
Upvotes: 1
Views: 1551
Reputation: 192287
Use Array.flatMap()
(not supported by IE/Edge):
const array = ['onions', 'tomatoes', 'garlic', 'fontina'];
const result = array.flatMap(item => [item, item]);
console.log(result)
Upvotes: 1
Reputation: 13973
Here is a way to do it with Array.reduce()
and the spread operator:
const array = ['onions', 'tomatoes', 'garlic', 'fontina'];
const result = array.reduce((acc, x) => ([...acc, x, x]), []);
console.log(result)
Array.reduce
iterates over your input array and calls the callback for each element. This callback is given two arguments, the first is the output from the last iteration, and the second one is the current array item.
The callback here returns a new array composed of the previous result of the callback (spread into the new array with the spread operator ...
) and the current item repeated twice.
To start the reducing process, we also need an initial value, here we give an empty array, (last argument to reduce
).
Here is a detailed description of the values of acc
and x
in the callback for the following reduction:
['a', 'b', 'c'].reduce((acc, x) => ([...acc, x, x]), []);
acc = [], x = 'a' => returns ['a', 'a']
acc = ['a', 'a'], x = 'b' => returns ['a', 'a', 'b', 'b']
acc = ['a', 'a', 'b', 'b'], x = 'c' => returns ['a', 'a', 'b', 'b', 'c', 'c']
Upvotes: 2
Reputation: 37755
Well the problem here is
string * 2 will not return 2 strings to you. it will return NaN
console.log('test'* 2) //NaN
What you're trying to achieve can be done by repeat
method.
console.log('test '.repeat(2))
Your expected output can be achieved like this
let arr = ['onions', 'tomatoes', 'garlic', 'fontina']
let output = arr.reduce((op,inp)=>(op.concat([inp,inp])),[])
console.log(output)
Upvotes: 0
Reputation: 330
Using vanilla JavaScript :
const ingredients = [ 'onions', 'tomatoes', 'garlic', 'fontina' ]
const ingredientsToRemove = [ 'onions', 'red pepper' ]
// Using Array.reduce method
const doubleIngredients = ingredients.reduce(
( array, ingredient ) =>
{
// If the ingredient has to be removed, return the array
// Else return the array with two times the current ingredient
return ingredientsToRemove.includes( ingredient ) ?
array
:
[ ...array, ingredient, ingredient ]
},
[]
)
console.log({ ingredients, doubleIngredients })
Upvotes: 0
Reputation: 39342
input
array using .map()
.Array()
constructor and filling it using .fill()
method of arrays..concat()
and spread operator.const input = ['onions', 'tomatoes', 'garlic', 'fontina'];
const dupeValues = (arr, factor) => [].concat(...arr.map(s => new Array(factor).fill(s)));
console.log(dupeValues(input, 2));
console.log(dupeValues(input, 3));
Upvotes: 1