-1

I need a simple function for creating new array from existing array. I have many arrays and it is not one-time operation, so I need a function.

Inside the function all is working fine and new array contains values I need. But after I execute it new array still is empty.

What could be a problem?

$(document).ready(function() {
  const $myArrOne = [
    'img/cakes/cake1.jpg',
    'img/cakes/cake2.jpg',
    'img/cakes/cake3.jpg',
  ];
  let $myArrTwo = [];

  const $myFunc = function(arrOne, arrTwo) {
    arrTwo = arrOne.map(item => {
      return (item.slice(0, -4) + '-small.jpg');
    });
    return arrTwo;
  };

  $myFunc($myArrOne, $myArrTwo);
  console.log($myArrTwo);
}
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • 3
    Your function looks weird, but why not just `$myArrTwo = $myFunc($myArrOne);` ? – Marc Feb 05 '21 at 09:11
  • The above also removes the need for the global variable, which should be avoided. – Rory McCrossan Feb 05 '21 at 09:14
  • Not quick to explain if you don't know the concept of "by reference" and "by value" - maybe this will help: https://stackoverflow.com/questions/7744611/pass-variables-by-reference-in-javascript or maybe https://stackoverflow.com/questions/373419/whats-the-difference-between-passing-by-reference-vs-passing-by-value – freedomn-m Feb 05 '21 at 09:14
  • In your case: `arrTwo = ` changes where arrTwo points to, so you essentially do `function(arrOne) { var arrTwo =` - the arrTwo that you pass in the parameters is thrown away because you've made it something else – freedomn-m Feb 05 '21 at 09:17
  • thanks to all for the advices – sepia__plot Feb 05 '21 at 09:44

1 Answers1

0

The problem is that you don't assign the result (array) returned by your function to anything. You simply create a new array variable inside the function and nothing more.

You can fix it like this:

const $myArrOne = [
    'img/cakes/cake1.jpg',
    'img/cakes/cake2.jpg',
    'img/cakes/cake3.jpg',
];

const $myFunc = arrOne =>
    arrOne.map(item =>
        item.slice(0, -4) + '-small.jpg');

let $myArrTwo = $myFunc($myArrOne);
console.log($myArrTwo);
Valery
  • 295
  • 2
  • 12