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);
Related
I'm trying to remove an item from an array using the indexOf() with splice() technique suggested. This is what's happening
let someArray: string[] = [first, second, third, fourth, fifth, sixth];
let newArray: string[] = someArray.splice(3, 1);
console.log(newArray);
//deisred result = [first, second, third, fifth, sixth]
//result I'm getting = [fourth]
That's not what virtually every article I've come across says should happen. Can someone shed light on this?
UPDATE
I discovered this problem in my code when I was only ghetting 1 result where I was expecting more and tracked it back to this point.
Because when you splice an array you are mutating it, which means you are changing the original array. You're storing the result (the element you're splicing from the array) within the "newArray" variable that you have created here. So this:
var arr = [1, 2, 3, 4];
var mine = arr.splice(1, 1);
console.log(mine);
console.log(arr);
would return the original ray minus index one if we print arr to the console, and will return [2] if we print mine to the console. To get the output you're expecting, you would have to perform a different operation such as iterating through the array and utilizing splice differently. Here is an example:
var arr = [1, 2, 3, 4];
var mine = [];
for(var i = 0; i < arr.length; i++) {
if(i !== 3) {
mine.push(arr[i]);
}
}
Now I am not mutating the original array, and I am simply pushing the elements to a new array.
But if you want to simply mutate the original array and not store the new array in some sort of variable you can simply splice the original array:
var arr = [1, 2, 3, 4];
arr.splice(3, 1);
console.log(arr);
However, if you are passing it to a function, i'd probably not mutate an array outside of the function, and i'd simply return a value and store that value in a new variable:
var arr = [1, 2, 3, 4];
function deleteIndex(ar, i) {
var a = [];
ar.forEach(function(elt, index) {
if(index === i) {
}
else {
a.push(elt);
}
});
return a;
}
var newArr = deleteIndex(arr, 3);
console.log(newArr);
This way you can delete any index, or pass a function and criteria that you would want to use to determine if an index should be deleted, without changing to top-level structure of your original array by utilizing functional programming. There are also some function in the underscore module that can help you if that's the case.
I'm trying to delete max value from arMin and min value from arMax, but arr (is a const!) changes too! I don't know why. I am using Google Chrome version 65.0.3325.181.
'arr' is only one time declared and it shouldn't do nothing with that. I can't understand that. Tried with delete, but it's turning numbers into 'empty', but works the same and changes const too!
It's my first post, so if I do something wrong please forgive me.
const arr = [1, 2, 3, 4, 5];
let arMin = arr;
let arMax = arr;
let min = arMin.indexOf(Math.min.apply(null, arMin));
let max = arMax.indexOf(Math.max.apply(null, arMax));
arMin.splice(max, 1);
arMax.splice(min, 1);
console.log(arMin); // [2,3,4]
console.log(arMax); // [2,3,4]
console.log(arr); // [2,3,4]
The value of arr is a reference to an array.
You cannot change that. It will always be a reference to that array.
Arrays are mutable though, so you can change values in the array. const won't prevent that.
If you want arMin and arMax to be different arrays, then you need to make a copy of the array and not just copy the value of arr (which is a reference to that array).
const makes the reference constant, not the value.
You can't make arr point to something else, but you can change its values.
Note: other languages, Dart comes to mind, have the ability of specifying constant values. That's not the case of JavaScript.
When you make an array const then you can not change the reference
const arr = [1,2,3]
arr = [4,5,6] \\ Throws errors; You can not change const reference
arr[1] = 6; \\ Works fine. You are not changing the const reference. You are just mutating the array.
const x = 5; \\ Here constant is the value
x = x + 1; \\ Error. You can not change the constant value;
As a constant, you can't reassign its value, in this case, it contains the reference to the array.
But the array itself is not immutable.
An example would be:
const arr = [0,1,2,3,4,5];
arr = 'foo' // You cannot do that
arr.push(6) // That works fine. result: [0,1,2,3,4,5,6]
To complete previous answer, to make an exact copy of array instead of copying reference, you should do something like this :
const arr = [1, 2, 3, 4, 5];
let arMin = [...arr]; // We use spread operator to create new array from original one.
let arMax = [...arr];
let min = arMin.indexOf(Math.min.apply(null, arMin));
let max = arMax.indexOf(Math.max.apply(null, arMax));
arMin.splice(max, 1);
arMax.splice(min, 1);
console.log(arMin); // [1, 2, 3, 4]
console.log(arMax); // [2, 3, 4, 5]
console.log(arr); // [1, 2, 3, 4, 5]
--- EDIT 1 ---
i use TypeScript synthax to illustrate type
const arr = [1, 2, 3, 4, 5];
arr.push(6); // Is allow.
const object: {id: number, title: string} = {id: 1, title: 'Yanis'};
object.id = 2; // Is allow.
const myString: string = 'yanis';
myString = 'Jackob'; // Not allow.
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 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)