Populating another array from array - Javascript - javascript

Very simple thing I am trying to do in JS (assign the values of one array to another), but somehow the array bar's value doesn't seem affected at all.
The first thing I tried, of course, was simply bar = ar; -- didn't work, so I tried manually looping through... still doesn't work.
I don't grok the quirks of Javascript! Please help!!
var ar=["apple","banana","canaple"];
var bar;
for(i=0;i<ar.length;i++){
bar[i]=ar[i];
}
alert(ar[1]);
And, here is the fiddle: http://jsfiddle.net/vGycZ/
(The above is a simplification. The actual array is multidimensional.)

Your code isn't working because you are not initializing bar:
var bar = [];
You also forgot to declare your i variable, which can be problematic, for example if the code is inside a function, i will end up being a global variable (always use var :).
But, you can avoid the loop, simply by using the slice method to create a copy of your first array:
var arr = ["apple","banana","canaple"];
var bar = arr.slice();

copy-or-clone-javascript-array-object
var a = [ 'apple', 'orange', 'grape' ];
b = a.slice(0);

In ES6 you can use Array.from:
var ar = ["apple","banana","canaple"];
var bar = Array.from(ar);
alert(bar[1]); // alerts 'banana'

You have two problems:
First you need to initialize bar as an array:
var bar = [];
Then arr should be ar in here:
for(i=0;i<arr.length;i++){
Then you'll get alerted your banana :)

With ES6+ you can simply do this
const original = [1, 2, 3];
const newArray = [...original];
The documentation for spread syntax is here
To check, run this small code on dev console
const k = [1, 2];
const l = k
k === l
> true
const m = [...k]
m
> [1, 2]
k === m
> false

You have misspelled variable ar
Try this
for(i=0;i<ar.length;i++){
bar[i]=ar[i];
}
alert(ar[1]);

The problem probably here in the for loop statement:
for(i=0;i<ar.length;i++){
bar[i]=ar[i];
}
alert(ar[1]);
You need to fix to ar.length instead of arr.length. And it's better to initialize bar as: var bar = [].

In your code, the variable arr in the for loop is not the same as your original array ar: you have one too many r.

Related

pushing into an array inside an object using function it's returning Number instead of the value of pushed array [duplicate]

Are there any substantial reasons why modifying Array.push() to return the object pushed rather than the length of the new array might be a bad idea?
I don't know if this has already been proposed or asked before; Google searches returned only a myriad number of questions related to the current functionality of Array.push().
Here's an example implementation of this functionality, feel free to correct it:
;(function() {
var _push = Array.prototype.push;
Array.prototype.push = function() {
return this[_push.apply(this, arguments) - 1];
}
}());
You would then be able to do something like this:
var someArray = [],
value = "hello world";
function someFunction(value, obj) {
obj["someKey"] = value;
}
someFunction(value, someArray.push({}));
Where someFunction modifies the object passed in as the second parameter, for example. Now the contents of someArray are [{"someKey": "hello world"}].
Are there any drawbacks to this approach?
See my detailed answer here
TLDR;
You can get the return value of the mutated array, when you instead add an element using array.concat[].
concat is a way of "adding" or "joining" two arrays together. The awesome thing about this method, is that it has a return value of the resultant array, so it can be chained.
newArray = oldArray.concat[newItem];
This also allows you to chain functions together
updatedArray = oldArray.filter((item) => {
item.id !== updatedItem.id).concat[updatedItem]};
Where item = {id: someID, value: someUpdatedValue}
The main thing to notice is, that you need to pass an array to concat.
So make sure that you put your value to be "pushed" inside a couple of square brackets, and you're good to go.
This will give you the functionality you expected from push()
You can use the + operator to "add" two arrays together, or by passing the arrays to join as parameters to concat().
let arrayAB = arrayA + arrayB;
let arrayCD = concat(arrayC, arrayD);
Note that by using the concat method, you can take advantage of "chaining" commands before and after concat.
Are there any substantial reasons why modifying Array.push() to return the object pushed rather than the length of the new array might be a bad idea?
Of course there is one: Other code will expect Array::push to behave as defined in the specification, i.e. to return the new length. And other developers will find your code incomprehensible if you did redefine builtin functions to behave unexpectedly.
At least choose a different name for the method.
You would then be able to do something like this: someFunction(value, someArray.push({}));
Uh, what? Yeah, my second point already strikes :-)
However, even if you didn't use push this does not get across what you want to do. The composition that you should express is "add an object which consist of a key and a value to an array". With a more functional style, let someFunction return this object, and you can write
var someArray = [],
value = "hello world";
function someFunction(value, obj) {
obj["someKey"] = value;
return obj;
}
someArray.push(someFunction(value, {}));
Just as a historical note -- There was an older version of JavaScript -- JavaScript version 1.2 -- that handled a number of array functions quite differently.
In particular to this question, Array.push did return the item, not the length of the array.
That said, 1.2 has been not been used for decades now -- but some very old references might still refer to this behavior.
http://web.archive.org/web/20010408055419/developer.netscape.com/docs/manuals/communicator/jsguide/js1_2.htm
By the coming of ES6, it is recommended to extend array class in the proper way , then , override push method :
class XArray extends Array {
push() {
super.push(...arguments);
return (arguments.length === 1) ? arguments[0] : arguments;
}
}
//---- Application
let list = [1, 3, 7,5];
list = new XArray(...list);
console.log(
'Push one item : ',list.push(4)
);
console.log(
'Push multi-items :', list.push(-9, 2)
);
console.log(
'Check length :' , list.length
)
Method push() returns the last element added, which makes it very inconvenient when creating short functions/reducers. Also, push() - is a rather archaic stuff in JS. On ahother hand we have spread operator [...] which is faster and does what you needs: it exactly returns an array.
// to concat arrays
const a = [1,2,3];
const b = [...a, 4, 5];
console.log(b) // [1, 2, 3, 4, 5];
// to concat and get a length
const arrA = [1,2,3,4,5];
const arrB = [6,7,8];
console.log([0, ...arrA, ...arrB, 9].length); // 10
// to reduce
const arr = ["red", "green", "blue"];
const liArr = arr.reduce( (acc,cur) => [...acc, `<li style='color:${cur}'>${cur}</li>`],[]);
console.log(liArr);
//[ "<li style='color:red'>red</li>",
//"<li style='color:green'>green</li>",
//"<li style='color:blue'>blue</li>" ]
var arr = [];
var element = Math.random();
assert(element === arr[arr.push(element)-1]);
How about doing someArray[someArray.length]={} instead of someArray.push({})? The value of an assignment is the value being assigned.
var someArray = [],
value = "hello world";
function someFunction(value, obj) {
obj["someKey"] = value;
}
someFunction(value, someArray[someArray.length]={});
console.log(someArray)

I need to show on console the result with two arrays using pop and shift methods

Given arrays are array1 and array2
Array1: ['A']
Array2: ['B','C','D','E','F','G','H','I']
Result: ['A','I','B','H','C','G','D','F','E']
How do i achieve something like this with .pop() and .shift().
I have tried
console.log(`array1: ${array1}`);
console.log(`array2: ${array2}`);
var removedItem = array2.pop();
var addedItem = array2.unshift(removedItem);
var array3 = array1.concat(array2);
console.log(`Lopputulos: ${array3}`);
For the current use case, but I think you have not described your question clearly, try to write it again with some edge case.
A current example is very trivial and so probably I still think the below solution will need a little tweaking.
But based on the current problem statement, I am writing this answer.
let a1 = ['A'];
let a2 = ['B','C','D','E','F','G','H','I'];
let sol = [...a1];
while(a2.length){
sol.push(a2.pop());
sol.push(a2.shift());
}
console.log(sol)

Javascript array concatenation

I have three variables a, b and c. I have to insert these into an array called arr. On calling function click, these variables should get pushed into arr array. eg. if i call click with arg 1,2 & 3 then array should be [1,2,3], now when I will pass the args 6,7 then the array should be [1,2,3,6,7].
In the code below, I tried to use concat method to get the desired result but i was unsuccessful.Is there any way around this?
function click(a,b,c){
var A=a;
var B=b;
var C=c;
var arr=[]
var newArr=[A,B,C]
arr.concat(newArr);
console.log(arr);
}
click(10,11,12);
click(12,13,14);
Declare a global array outside of the function and then after push values into it.
var arr = [];
function click(a,b,c){
arr.push(a, b, c)
}
click(10,11,12);
click(12,13,14);
console.log(arr);
The problem with your code is that, you are concatenating to the array but not considering the return value.
arr = arr.concat(newArr);
Then declare the array global to hold the values for every click.
function click(arr, a, b, c){
arr.push(a, b, c);
console.log(arr);
}
var arr = [];
click(arr, 10, 11, 12);
click(arr, 12, 13, 14);
If you don't want your arr outside your function, another approach is storing your arr inside click scope then call it anywhere (it doesn't pollute your global scope):
let click = (function (arr) {
return function (a,b,c) {
var A=a;
var B=b;
var C=c;
var newArr=[A,B,C]
arr = arr.concat(newArr);
console.log(arr);
}
})([])
click(10,11,12);
click(12,13,14);
First of all. You should either define arr outside your function or pass arr into function as a parameter.
Second one. Function concat returns concatenated arrays and left original arrays unchanged. So you need something like arr=arr.concat(newArr)
Destructuring assignment can be used to functionally concatenate
variables with arrays.
See below for a practical example.
// Input.
const input = [1, 2, 3]
// Click.
const click = (array, ...arguments) => [...array, ...arguments]
// Output.
const output = click(input, 4, 5, 6)
// Proof.
console.log(output)
Your Problem here is that the concat function returns a new array instance with the elements:
Check Here
function click(a,b,c){
var A=a;
var B=b;
var C=c;
var arr=[]
var newArr=[A,B,C]
arr = arr.concat(newArr);
// concat does not change the ref itself
console.log(arr);
}
click(10,11,12);
click(12,13,14);

What is the right way to create and access multidimensional array in javascript

Simple issue I am facing.
arr = [[1,2,3],[3,4,5],[6,7,8]];
x = arr[0];
x[0] = 2; //x returns [2,2,3]
At the same time arr is also updated to [[2,2,3],[3,4,5],[6,7,8]]
How can I prevent this.I don't want arr to change and why does this happen?
The = operator does not make a copy of the data.
The = operator creates a new reference to the same data.
An easy fix would be to do the following when assigning the value of x:
x = arr[0].slice();

how to copy contents of one array into another. Javascript

i have a main array as
arrayVariable = [1,2,3];
and i want another to variables to have the same content as above. If i do
anotherVariable = arrayVariable;
It will just reference that array and they wont be independent of each other.
I tried this solution, but it didnt work.
var anotherVariable = arrayVariable.slice();
Edit:
Another question,
while passing array through a function, does it pass the array or is it passed by reference?
like
var array = [];
someFunction(array);
function someFunction(array){};
Check the below code, look they are independent.
arrayVariable = [1,2,3];
var anotherVariable = arrayVariable.slice(); // or .concat()
arrayVariable[0] = 50; // Hopefully it should not change the value of anotherVariable
alert(anotherVariable); // Look value of anotherVariable is not changed
you can try
var aa = [1,2,3,4,5,6];
var bb = [].concat(aa);//copy aa array to bb, they are now independent of each other.
hope helps.
You can do it using a loop.
arrayvariable=[1,2,3];
for (var i=0;i<arrayvariable l.length;i++)
//while could also be used.
{
anothervariable[i]=arrayvariable[i];
}

Categories

Resources