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
Related
let arr = new Set();
arr.add([1,1,1,1]);
arr.add([1,1,1,1]);
console.log(arr);
Why output is [[1,1,1,1], [1,1,1,1]] ?
If I want to remove duplicate elements, I should taking something?
(I want to making [[1,1,1,1]])
The object references are different. Similar to how {}=={} returns false.
You can use JSON.stringify() to get past this:
console.log([1,1,1,1,] === [1,1,1,1]);
let arr = new Set();
arr.add([1,1,1,1]);
arr.add([1,1,1,1]);
let ans = new Set([...arr].map(x => JSON.stringify(x)));
console.log(ans);
this will be helpful to revert back as array items was before
Array.from(new Set([[1,2,3,4], [1,2,3,4]].map(JSON.stringify)), JSON.parse);
It's because you add an array inside your set, SET does not deep compare your element and [1, 1] !== [1, 1] because they share a different reference.
I think you wanted to do
arr = new Set();
arr.add(...[1, 1, 1, 1]);
arr.add(...[1, 1, 1, 1]);
console.log(arr);
I'm learning about arrays in Code.org.
So there are methods like insertItem(list, index, item) in code.org, but as I read many books about arrays in javaScript, none of them talked about the insertItem Method.
I wanted to know if insertItem is generic to JS or is it just specifically made for the code.org platform?
That method is only on code.org
https://docs.code.org/applab/insertItem/
But JS has a similar method you can use:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
insertItem() is purely code.org
https://docs.code.org/applab/insertItem/
To do this in regular javascript, you would:
If you wanted to insert the item into the end of the array, you would use .push()
var array = [0, 1, 2];
console.log(array);
array.push("item");
console.log(array);
If you wanted to replace an item in the array (in which you know the index), you would use array[index] = item;
var array = [0, 1, 2];
console.log(array);
array[1] = "item";
console.log(array);
If you wanted to replace an item in an array by knowing the value, but not the index, you would use array[array.indexOf(value)] = item;
var array = [0, 1, 2];
console.log(array);
array[array.indexOf(1)] = "item";
console.log(array);
Finally, if you wanted to insert an item into the array, you would use .splice(). To insert an item after index 2, you would use array.splice(2, 0, item).
var array = [0, 1, 2];
console.log(array);
array.splice(1, 0, "item");
console.log(array);
Code.org probably uses the following function to make life easier for you:
var array = [0, 1, 2];
function insertItem(list, index, item) {
list.splice(index, 0, item);
return list;
}
console.log(array);
array = insertItem(array, 1, "item");
console.log(array);
There is no method by name insertItem for Array in javascript. Also it seems insertItem(list, index, item) is a function and it accepts three arguments.
You can get list of javascript array methods in this link
There's no JavaScript function named insertItem - however, there's an almost identical method named splice - syntax like list.splice(index, 0, item):
var list = [1, 2, 4];
var item = 3;
var index = 2;
list.splice(index, 0, item);
console.log(list);
I have an array and I want to put it in another array using indexes.
For example:
arry[1].push(sub_array_1)
array[2].push (sub_array_2)
But I get an error if I write:
var sub_array_1 = [1, 2, 2, 2, 2];
arry[1].push(sub_array_1)
Using spread operator
var subArray = [1, 4, 6, 7];
var mainArray = [6, 7, 8];
var index = 1;
mainArray = [...mainArray.slice(0, index), subArray, ...mainArray.slice(index)];
Assuming:
var arry = [9,8,7];
var sub_array_1 = [1,2,2,2,2];
If you are trying to insert sub_array_1 into arry, as a single element, just use splice directly:
arry.splice(1, 0, sub_array_1);
The result will be:
[9,[1,2,2,2,2],8,7]
On the other hand, if you are trying to insert the contents of sub_array_1 before the second element of arry, you can do something like this:
Array.prototype.splice.apply(arry, [1, 0].concat(sub_array_1));
The result will be:
[9,1,2,2,2,2,8,7]
Here is a more general function:
function insert(arrayDest, index, arraySrc) {
Array.prototype.splice.apply(arrayDest, [index, 0].concat(arraySrc));
}
[EDITED]
Starting with ES6, you can simplify the above code using the spread operator (...). For example:
function insert(arrayDest, index, arraySrc) {
arrayDest.splice(index, 0, ...arraySrc);
}
You're using wrong syntax! Follow the either below mentioned approach.
var sub_array_1 = [1,2,2,2,2];
arry[1] = sub_array_1;
// OR
var sub_array_1 = [1,2,2,2,2];
arry.push(sub_array_1);
.push(ele) will add an item to an array, thereby incrementing the length of array by 1. Remember array index starts at 0.
If you need to add an item(array/object/other) to a particular index, use [index]. Eg: arry[0] = [1,23]; arry[1] = [4,5,6,7];
obj.arrayOne.push(arrayLetters);
or
obj['arrayOne'].push(arrayLetters);
let array = []
array.push({"index": 0, "value":100})
console.log(array)
maybe it helping for you
I'm wondering what is the fastest way in JavaScript to move an element from the beginning of an Array to the end. For example if we have
[8,1,2,3,4,5,6,7]
And we want: [1,2,3,4,5,6,7,8]
I want to move the first element to the end. I was thinking about switching element 0 with element 1, after that switching element 1 with element 2 and so on until the 8 is at the and (basically how bubblesort works). I was wondering if there is a faster way to bring the first element to the end.
I will be using small Arrays (around 10 elements), and I want to avoid shift() since it's pretty slow.
This is what I have now on chrome it's 45% faster than normal shift+push: http://jsperf.com/shift-myfunc
The arrays will have objects in them for a game.
Use the shift() and push() functions:
var ary = [8,1,2,3,4,5,6,7];
ary.push(ary.shift()); // results in [1, 2, 3, 4, 5, 6, 7, 8]
Example:
var ary = [8,1,2,3,4,5,6,7];
console.log("Before: " + ary);
ary.push(ary.shift()); // results in [1, 2, 3, 4, 5, 6, 7, 8]
console.log("After: " + ary);
Use shift and push
var a = ["a","b","c"];
var b = a.shift();
a.push(b);
or
var b = a.shift();
a[a.length] = b;
Edit Based on updated question
What is going to be the fastest? Really depends on content of the array and what browser/version!
Now what are the ways to remove the first index?
shift()
splice()
slice()
Now what are the ways to add to the last index?
push()
array[array.length]
concat() -- not even going to try
Other ways
for loop - make new array [going to be horrible on large arrays]
JSPerf:
http://jsperf.com/test-swapping-of-first-to-last
What is really the fastest?
What is the fastest really depends on what you are doing with the array. If you are just using the first index, it will be fastest just to make your code read an index and not shift the values. If you are using all the indexes, than just loop and through and when you get to the end start back at zero. Basic counters.
And here is a sweet ES6 version
let arr = [1,2,3,4,5,6]
const [first, ...rest] = arr;
arr = [...rest,first]
Use splice to get the first element
var first = array.splice(0,1);
Then push to make if the last.
Since the return value of the splice method is an array, you have to say
array.push(first[0]);
Working example here: JSFIDDLE
Just in case you want to put any element to the end:
var ary = [8,1,2,3,4,5,6,7];
ary.push(ary.splice(position, 1)[0]);
for position just wrap this in a forEach.
var a = [1,2,3,4,5,6,7,8];
var b= a[7];
var c = a.slice(1, 8);
c.push(b);
Edit: It's probably better to just shift, like epascarello did in his answer.
With ES20...
const newArr = [
...arr.slice(1),
arr[0]
];
one more flavour
var arr = [0, 1, 2];
arr = arr.concat(arr.shift())
concat can add not just a element but another array at the end or beginning
Updating the arrays moving elements from one extreme to the other:
const array = ['First', 'Second', 'Third', 'Fourth'];
const next = [...array]
next.push(next.shift())
console.log(next); // [ 'Second', 'Third', 'Fourth', 'First' ]
const prev = [...array]
prev.unshift(prev.pop())
console.log(prev); // [ 'Fourth', 'First', 'Second', 'Third' ]
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)