Michael DeS
Michael DeS

Reputation: 21

multiply each element in array by 2 using 'for' loop

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

Answers (5)

Ori Drori
Ori Drori

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

jo_va
jo_va

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]), []);
  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']

Upvotes: 2

Code Maniac
Code Maniac

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

sphinxplayer
sphinxplayer

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

Mohammad Usman
Mohammad Usman

Reputation: 39342

  • 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));

Upvotes: 1

Related Questions