Moving element inside an object in javascript [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JavaScript Array rotate()
I have a tricky question for you. I have an object who contain different values and I want to change the index of on element so My first element has to become the last or the third or whatever I want. Is that possible in javascript ??
var object = [{0},{1},{2}]
to
var object = [{2},{0},{1}]
This is an example of what I would like to do.
Thanks in advance.

Your from and to example is a little hard to understand the intent, but based on the body of your question asking
My first element has to become the last or the third or whatever I want
Writing a method to swap 2 elements in an array is easy enough:
function swapElements(a, x, y){
var temp = a[x];
a[x] = a[y];
a[y] = temp;
}
Live example: http://jsfiddle.net/pwY9L/

I assume you mean:
var array = [0,1,2];
It doesn’t really matter if the array contains numbers, objects or whatever. If you want to modify this array, there are many ways to do this in javascript andyou can read up about all the Array prototypes here: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array
F.ex, move the last one and place it first:
array.unshift(array.pop());

Related

JS arrays - advanced assignment [duplicate]

This question already has answers here:
How do I replace a character at a particular index in JavaScript?
(30 answers)
Closed 6 years ago.
This is related to the arrays in Javascript, which I am trying to use in a complex logic.
Consider the following code:
a['a1'] = 'AJA'
We know that, this is same as a.a1 = 'AJA' (provided proper definitions were given).
So, if we go ahead and interpret this:
console.log(a.a1[0])
console.log(a.a1[1])
console.log(a.a1[2])
console.log(a.a1)
It logs :
A
J
A
AJA
Now, all I need is to assign a new character at the 4th position.
When I try a[a1][3] = 'Y' or a.a1[3] = 'Y' and then try console.log(a.a1), It still displays AJA instead of AJAY.
I know that we can do this using string concatenation, i.e.
a['a1'] = a['a1'] + 'Y' and get this accomplished.
But why wasn't the first method working? By what other ways can do this?
Strings are immutable. It means that if you create a string, you can't modify it anymore. So your a1 doesn't know anything about 4th character.
You can see this example. I try to change the second char of the already created string, but it will not be changed anymore.
let a = {};
a['a1'] = 'AJA';
a.a1[1] = 'A';
console.log(a.a1);
For more you can see MDN Documentation
As I know a[a1][3] or a.a1[3] is a string variable, you can treat it as:
var s = 'ss';
When you evaluate s[0] you'll get a string value. So when you assign any string value to s, you'll not get 'ss' + anyvalue but anyvalue instead. :)

Finding specific objects in array to remove [duplicate]

This question already has answers here:
Best way to find if an item is in a JavaScript array? [duplicate]
(8 answers)
Closed 7 years ago.
I have an array of data which stores an object with functions and other such info. I push these objects to the function for my draw function to execute.
But i do not know of a way to find a specific object in an array to remove it and thus stop drawing it.
For example i have an array structure like this:
var data = {
'fnc':function(){
updatePosition(spriteID);
drawSprite(spriteID);
},
'something':'here'
};
var drawOrder= [];
drawOrder.push(data);
There are many functions in this array and they are pushed dynamically depending on what i wish to draw.
What would be the best way to find the index of one of these objects and remove it from the array in this case?
indexOf() returns the index in the array of the element you're searching for, or -1. So you can do:
var index = drawOrder.indexOf("aKey");
if (index != -1)
drawOrder.splice(index, 1);
Splice:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
indexOf:
http://www.w3schools.com/jsref/jsref_indexof_array.asp
I'm not 100% this will answer your question cause is not clear at least to me.
If you want to remove the whole element but you are worried about founding the right index before actually splice the array you should use Array.indexOF
See this code below:
var data = {
'fnc':function(){
updatePosition(spriteID);
drawSprite(spriteID);
},
'type':'aabb'
};
var drawOrder= [];
drawOrder.push(data);
console.log(drawOrder);
drawOrder.splice(drawOrder.indexOf(data), 1);
console.log(drawOrder);
As the documentation reports:
The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

Javascript - refilling one array from another [duplicate]

This question already has answers here:
Copy array by value
(39 answers)
Closed 8 years ago.
I'm creating a simple question and answer game to help with revision and having trouble repopulating an array the second time around.
When a button is clicked the following code is executed.
if(setSelection == 0){
tempQuestions = chosenQuestion;
tempAnswers = chosenAnswer;
}
This works perfectly the first time.
When a correct answer is selected the following code removes the question and answer from temporary array, leaving the original intact.
tempQuestions.splice(randomQuestion,1)
tempAnswers.splice(selectedAnswer, 1);
When the button is pressed for a second time, after the 'game' is complete, the temporary array fails to refill even though I'm executing the same code.
Any ideas why the code above does not work on the second run?
EDIT
jsfiddle
You are creating a new reference to the same array, so when you modify the temp vars you also modify the object referenced by the chosen vars. You need to copy the array. A nice way is to add your own copy() prototype method to the Array object.
a shallow copy should do:
Array.prototype.copy = function(){
return this.slice(0);
}
If you need a deep copy
Array.prototype.copy = function(){
return JSON.parse(JSON.stringify(this));
}
Use it like this:
if(setSelection == 0){
tempQuestions = chosenQuestion.copy();
tempAnswers = chosenAnswer.copy();
}
Using .slice works.
tempQuestions = chosenQuestion.slice();
The slice() operation clones the array and returns reference to the original.

Javascript - array connect to another [duplicate]

This question already has answers here:
Copy array by value
(39 answers)
When I assign a variable to another variable does it not link them together?
(1 answer)
Closed 9 years ago.
I have really weird situation:
when I do that code:
var origin_array = [1,2,3];
var m = origin_array;
m.pop();
alert(origin_array);
origin_array value will be 1,2
eventhough I didn't changed it
but if I make that code:
var x = 5;
var y = x;
y--;
alert(x);
x still be 5, it won't be connected to "x" as you can see from the 1st example.
So my question is how do I make the "m" array unique, which not change the origin array?
You need to explicitly make a (shallow) copy or clone of origin_array:
var m = origin_array.slice(0);
This is not needed for primitive values, such as strings and numbers.
It's important to understand that although the above will prevent the issue you were experiencing, the same may happen again deeper down if you're dealing with more complex structures, and in some cases a "deep clone" is necessary.
Arrays are assigned by reference. That means that when you do this:
var origin_array = [1,2,3];
var m = origin_array;
m just points to the exact same array as origin_array. There is only one array and both origin_array and m point to it. If you modify it via either variable, they will both see the modification because you're modifying the one array that they both point to.
In javascript, both objects and arrays are assigned by reference like this. Assigning them does NOT make a copy. If you want an assignment to generate a copy, you have to explicitly make a copy. For an array, that is easy as you can just do:
var origin_array = [1,2,3];
var m = origin_array.slice(0); // makes a shallow copy
m.pop();
console.log(origin_array); // [1,2,3] because origin_array was not changed

copying an array of objects in javascript [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Copying array by value in javascript
How to copy an array of objects to another array in Javascript?
var qwerty1 = arr;
var qwerty2 = arr;
Both qwerty1 and qwerty2 may look different but point to the same reference.
I read somewhere that "assigning a boolean or string to a variable makes a copy of that value, while assigning an array or an object to a variable makes a reference to the value." So my two arrays post different operations return the same objects.
Any light in this regard?
The idiomatic way to copy an array in Javascript is to use concat:
var qwerty1 = arr.concat();
var qwerty2 = arr.concat();

Categories