I am trying to replicate Python's insert at index functionality in Javascript.
var index = [0,1,2,3,4]
var nums = [0,1,2,2,1]
const target = new Array(nums.length);
for (let i=0; i<index.length; i++) {
target.splice(nums[i], 0, index[i]);
};
console.log(target);
This produces the following output:
[ 0, 4, 1, 3, 2, <5 empty items> ]
However, if I run the following code:
var index = [0,1,2,3,4]
var nums = [0,1,2,2,1]
const target = [] //new Array(nums.length);
for (let i=0; i<index.length; i++) {
target.splice(nums[i], 0, index[i]);
};
console.log(target);
This produces the following output:
[ 0, 4, 1, 3, 2 ]
What is going on? The second output is the one I desire.
new Array(nums.length) will fill the array with 'empty slots' for that number.
const target = [] Will be [ ]
const target = new Array(5) will be [, , , , ]
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Array More info here.
when you initialize array like this :
const target = new Array(index.length);
This code will initiate "target" array with five empty box. in result it contain garbage value and it may affect your value after insertion.
But when you initialize like this :
const target = [];
This code will initiate "target" array without defining the size of it. it means you can insert n number of dynamic value inside this.
('n' denote the size of array)
So always use second option which is good practice to use javascript Array
Related
I am trying to add array of arrays dynamically in javascript. I need the data in the following format -
var dataArray = [[],[],[],.....,[]];
How can I initialize this kind of array? Suppose if I have three arrays to be added, I can initialize as follows -
var dataArray = [[],[],[]];
This will accept only three records to be added. But, what should I do in case of adding large number of arrays? Here I cannot know the amount of data I get as input.
I have tried using concat() and merge() methods, these are adding contents directly in to a single array, but that is not what I wanted.
Can any one please help me out on this?
You can build or add an array into an array like this:
var dataArray = [];
dataArray.push([1,2,3]);
dataArray.push([3,4,5]);
console.log(dataArray); // [[1,2,3], [3,4,5]]
Or, if you want to add elements to the sub-arrays:
var dataArray = [];
dataArray.push([1,2,3]);
dataArray.push([3,4,5]);
dataArray[0].push(4);
dataArray[1].push(9);
console.log(dataArray); // [[1,2,3,4], [3,4,5,9]]
You initialize a sub-array by assigning an array to the element of the outer array. You can then use array operations directly on the sub-array element:
// create a sub-array element
dataArray[2] = [];
dataArray[2].push(8);
dataArray[2].push(7);
console.log(dataArray[2]); // [8,7]
console.log(dataArray); // [[1,2,3,4], [3,4,5,9], [8,7]]
The key thing it appears you don't understand is that an array of arrays is just that. It's an outer array where each element in the outer array is itself an array. You use ordinary array methods to operate on either the outer array or the inner arrays. To operate on an inner array, you fetch that element from the outer array and then just treat it as an array. For example:
var dataArray = [];
dataArray.push([1,2,3]);
dataArray.push([3,4,5]);
console.log(dataArray); // [[1,2,3], [3,4,5]]
var innerArray = dataArray[0];
console.log(innerArray); // [1,2,3]
innerArray.push(12);
console.log(innerArray); // [1,2,3,12]
innerArray.legnth = 2;
console.log(innerArray); // [1,2]
innerArray.push(9,8,7);
console.log(innerArray); // [1,2,9,8,7]
innerArray.splice(1,2);
console.log(innerArray); // [1,8,7]
You have wrote "I am trying to add array of arrays dynamically in javascript"
The simple way is using Array.prototype.push method:
var arr1 = [1,2], arr2 = [3,4], arr3 = [5,6], arr4 = [7,8], arr5 = [9,10],
dataArray = [];
[].push.apply(dataArray, [arr1, arr2, arr3, arr4, arr5]);
console.log(JSON.stringify(dataArray, 0, 4));
The console.log output:
[
[
1,
2
],
[
3,
4
],
[
5,
6
],
[
7,
8
],
[
9,
10
]
]
There are tons of way you can do this. A simple one could be
var arrayN = n => Array(n).fill([])
document.write("<pre>" + JSON.stringify(arrayN(10)) + "</pre>")
On another thinking if you already have arrays of arrays then the most simplified way of concatenating them in place should be using the new spread operator like;
var arr = [[1,2,3],[1,3,5]],
brr = [[3,2,1],[7,8,9]];
arr.push(...brr);
document.write("<pre>" + JSON.stringify(arr) + "</pre>");
I have an array value as a with key:value pair. I wanted to map the same key array values as below format:
Expected Output: [abc: 1],[def:2,42,40]
Please find my code below:
var a = {"abc": 1, "def": 2, "def": 42, "def" : 40};
var array_keys = new Array();
var array_values = new Array();
for (var key in a) {
array_keys.push(key);
array_values.push(a[key]);
}
alert(array_keys);
alert(array_values);
It returns the values as
My output : [abc:def] [1,40]
Any help on this?
You can achieve something like what you want if you play around with your initial data structure:
Have an array of objects:
var a = [{abc: 1}, {def: 2}, {def: 42}, {def: 40}];
Set up a new object
var o = {};
And then loop over the data. For each object: if the key doesn't exist in o, the output object, add it and set its value to an array, otherwise just push the value of the object to the array.
for (var i = 0, l = a.length; i < l; i++) {
var key = Object.keys(a[i]);
if (!o[key]) { o[key] = []; }
o[key].push(a[i][key]);
}
And you end up with an object the values of which are arrays:
console.log(o); // {abc: [1], def: [2,42,40] }
Demo
var a = {"abc": 1, "def": 2, "def": 42, "def" : 40};
This is not possible. Object keys must be unique in javascript, so you can't add 3 different items with the same key ("def"). If you define multiple elements with the same key, at least chrome will take the last added value.
So answering your question: With the input provided there is no way to get you Expected output.
I have read this Swap rows with columns (transposition) of a matrix in javascript However, it did not work for me (because I still stupi).
There are numbers of arrays each as individual colum like that:
id [1, 2, 3]
caption [one, two, three]
title [One, Two, Three]
I want to convert columns to row:
arr= [1, one, One]
...
Some code
var res = [];
for(i in this.fields) {
for(j in this.fields[i].value) {
res[j][i] = this.fields[i].value[j];
}
}
it give me "TypeError: can't convert undefined to object "
In php this method works fine, but could somebody point me how to do it in js. Thanks in advance.
UPDATE for simplication
var arr = [];
arr[0] = [];
arr[6][0] = 5;
/*
Exception: can't convert undefined to object
#Scratchpad/1:4
*/
When we scan common string we iterate with indexes like 0-0, 0-1, 0-2 until end-of-row when starts again 1-0 and so on. But here I need 0-0, 1-0, 2-0 end of col and again 1-0, 1-1, 1-1 ...
UPDATE for "this". Just add a cople of lines:
console.log(this.fields[i].value[j]);
console.log('indexes: i='+i, 'j='+j);
and as could you see there are no undefined values
4
indexes: i=0 j=0
1
indexes: i=1 j=0
1
indexes: i=2 j=0
one
indexes: i=3 j=0
One
indexes: i=4 j=0
There are a few mistakes in your source code. We don´t know how your this.fields value looks like, but for the sake of your code snippet let it look like that:
this.fields = [
{ value: [1, 2, 3] },
{ value: [4, 5, 6] },
{ value: [7, 8, 9] }
]
If your this.fields variable looks like that, you are not so far away from the solution. Your error message says TypeError: can't convert undefined to object, so I am guessing your variable does not look like described.
When we transform your data in a form that looks like my example, your are not so far away from the solution in your code snippet. The problem is res does not know, that its second dimension is supposed to consist of arrays, because you never defined that. We can fix that by adding if(i === 0) res[j] = [];.
So with the described structure and our little fix, it should work:
var res = [];
for(i in this.fields) {
for(j in this.fields[i].value) {
if(i === 0) res[j] = [];
res[j][i] = this.fields[i].value[j];
}
}
For sure one error is within the loop itself. On the first iteration res[j] exists, but inside the inner loop res[j][i] is not defined and will throw an error. You could fix it by checking if the element already exists:
var res = [];
for(i in this.fields) {
for(j in this.fields[i].value) {
if( !res[j] ) { res[j] = []; }
res[j][i] = this.fields[i].value[j];
}
}
I have an array:
array = [S1,S2,S3,S4_a,S4_b,S5_a,S5_b,S5_c etc....]
How can I delete all the objects from the last object down to what ever index I give it ?
array.delte(last:S3)
So, I would like to to delete downto S3, so everything after it must be deleted
new_array = [S1,S2,S3]
It think you want splice:
array.splice(0, index);
var a = [1, 2, 3, 4, 5, 6];
a = a.splice(0, 3);
// a is now [1, 2, 3]
or, if you don't know the position of 3:
a = a.splice(0, a.indexOf(3) + 1);
Be aware though, that some browsers do not implement Array.indexOf so consider using a library such as jQuery or prototype.
Use javascript
array splice function , or array slice function. see : http://jsfiddle.net/
var origArray = new Array('a','b','c','d','e','f','g');
var myIndex = 4;
var origArray = origArray.slice(0,myIndex); // is now ['a','b','c','d']
Deleting all after index:
var index=3;
var arr1=['a','b','c','d','e','f','g'];
arr1.length=index; // now arr1 contains ['a','b','c']
Deleting all before index:
var index=3;
var arr1=['a','b','c','d','e','f','g'];
var arr2=arr1.slice(index); // now arr2 contains ['d','e','f','g']; arr1 remains unchanged
var NewdateData[] = [1,2,3,4,5,6,7,8,9,1,2,1,23,45,56]
This NewdateData is dynamically filled from database depending upon the selection made from the user interface.
I am using this NewdateData for displaying under the X axis Charts.
The issue I am facing is that, the values are not taken till the end , I want to have the last value to have under the X axis Labels.
xaxis: {tickFormatter: function(n)
{
var k = Math.round(n);
return NewdateData[k];
}
I am using flotr.
You can get the last value of an array with:
NewdateData[NewdateData.length-1];
Very late to the party, but for posterity: in ES2015/ES6 you can use Array.prototype.slice. Doesn't mutate the array and a negative number gives you elements from the end of the array as a new array.
So to get the last element:
let arr = [1, 2, 3, 4, 5];
let last = arr.slice(-1); // last = 5
I don’t have enough points to comment on Radman’s post., but his solution is wrong.
let arr = [1, 2, 3, 4, 5]; let last = arr.slice(-1); // last = 5
Returns [5], not 5.
The slice() method returns a shallow copy of a portion of an array
into a new array object selected from begin to end (end not included).
The original array will not be modified.
The correct answer:
let arr = [1, 2, 3, 4, 5];
let last = arr.slice(-1)[0];
References: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice
Just do it with the map function.
this is the array what I want to pick the last item from it:-
const animals = ['Dodo', 'Tiger', 'Penguin', 'Dodo'];
loop over the array using map function to use the index parameter and compare it with animals array length:-
animals.map((animal, index) => animals.length -1 === index ? console.log("last item selected :)" + animal) : console.log("i'm not the last item"))
Now we are living with ES6 features
var arr = [1,2,3,4,5,6]
const [a, ...b] = arr.reverse();
console.log(a)
A simple and convenient way is to use Array.prototype.at()
function returnLast(arr) {
return arr.at(-1);
}
const cart = ['apple', 'banana', 'pear'];
const lastItem = returnLast(cart);
console.log(lastItem) //pear
or just
const lastItem = cart.at(-1)