1

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']
2
  • 1
    string * 2 will not return 2 strings to you. it will return NaN Commented Feb 10, 2019 at 16:50
  • 1
    [Hint] : Look into using Array#push() twice in your loop Commented Feb 10, 2019 at 16:51

5 Answers 5

2

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]), []);
  1. acc = [], x = 'a' => returns ['a', 'a']
  2. acc = ['a', 'a'], x = 'b' => returns ['a', 'a', 'b', 'b']
  3. acc = ['a', 'a', 'b', 'b'], x = 'c' => returns ['a', 'a', 'b', 'b', 'c', 'c']
Sign up to request clarification or add additional context in comments.

2 Comments

As you can see user is new to programming. adding explanation to answer will do wonder to op and future readers to.
Thank you, this is a good point, I will add more explanations
1
  • Iterate over input array using .map().
  • Initialize new array using Array() constructor and filling it using .fill() method of arrays.
  • Finally you can convert array of arrays to a single array using .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));

3 Comments

As you can see user is new to programming. adding explanation to answer will do wonder to op and future readers to.
Thanks a lot everyone for your help.. I learned a ton from every response and using figured it with the array.reduce() and spread operator... Thanks for your time...
For keeping it generic +1
1

Use Array.flatMap() (not supported by IE/Edge):

const array = ['onions', 'tomatoes', 'garlic', 'fontina'];

const result = array.flatMap(item => [item, item]);

console.log(result)

Comments

0

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 })

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.