0

I've one object, where one value is array of numbers and I call two functions, first function sorts data and display it, second function just display it.

problem is that, in second function, data is also sorted. (I'm not sorting there, data have come already sorted)

function1(data);
function2(data);

How can I fix it?

aw-bubakik
  • 301
  • 1
  • 2
  • 10

4 Answers4

2

One simple solution to this would be create a copy of the object and then using it.

You can create a copy of the object, if don't want that using:

b = Object.create(a)

In this case b is a copy of a but if you make changes in a, it won't reflect in b. For more info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create

Reason: In javascript objects are passed by reference http://www.w3schools.com/js/js_function_parameters.asp

Ayush
  • 311
  • 1
  • 10
2

Create clone inside sorted function before sorting it

Try like this

var cloneData=data.slice();
Anik Islam Abhi
  • 25,137
  • 8
  • 58
  • 80
1

your function1 is sorting the data which means the data will be sorted when you call function2, what you can do is in function1 take in data, but create a new variable from data and then update that so the original data is never changed

However displaying some code for function1 and function2 would really help us provide some useful code :)

Canvas
  • 5,779
  • 9
  • 55
  • 98
0

You will need to duplicate your object to do this. It has to do with object refencing and such.

VERY short explanation (way too short to do it any justice) is that function1 and function2 are using the same array, so when function1 changes it, this is visible in function2 afterwards. read up in this question here, this is definitely something you should research as a programmer.

var data = ['b', 'c', 'a'];
var sortedData = data.slice(0); // shallow copy, objects in the array are not copied

call the function that sorts with sortedData, call the function that only displays with data

Read up more about object references and primitive values to understand how changing values in one array is going to affect to other one, but if you aren't changing the values anymore this is not an issue you need to worry about.

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
Ward D.S.
  • 536
  • 3
  • 11