I have a problem with removing the first element of an array.
To be short, this is how my array looks like if I show it in console:
(11) [Array(4), Array(4), Array(4), Array(4), Array(4), Array(4), Array(4), Array(4), Array(4), Array(4), Array(4)]
0 : (4) ["2017-09-20T16:00:00-07:00", 188.125, 0, 1]
1 : (4) ["2017-09-20T17:00:00-07:00", 123.125, 0, 1]
2 : (4) ["2017-09-20T18:00:00-07:00", 114.25, 0, 1]
3 : (4) ["2017-09-20T19:00:00-07:00", 115, 0, 1]
4 : (4) ["2017-09-20T20:00:00-07:00", 113.25, 0, 1]
5 : (4) ["2017-09-20T21:00:00-07:00", 115.625, 0, 1]
6 : (4) ["2017-09-20T22:00:00-07:00", 114.75, 0, 1]
7 : (4) ["2017-09-20T23:00:00-07:00", 114, 0, 1]
8 : (4) ["2017-09-21T00:00:00-07:00", 112.625, 0, 1]
9 : (4) ["2017-09-21T01:00:00-07:00", 108.375, 0, 1]
10 : (4) ["2017-09-21T02:00:00-07:00", 111.125, 0, 1]
length : 11
__proto__ : Array(0)
I want to remove the first one, 0, I tried using .shift() but didn't work.
Like my array is called myArray.data and I tried myArray.data.shift() and I get this error message:
TypeError: Cannot read property '0' of undefined
at bundle.js:1554
at Function._.map._.collect (vendor.js:11761)
at renderChart (bundle.js:1547)
at bundle.js:1611
at Scope.$digest (vendor.js:34716)
at Scope.$apply (vendor.js:34986)
at bundle.js:259
at vendor.js:14387
at _fulfilled (vendor.js:13992)
at self.promiseDispatch.done (vendor.js:14021)
Any ideas how to solve this?
Later edit:
The code is inside a chart generation function, this is the whole snippet:
data: {
type: chartType,
columns: [
['x'].concat(_.map(myArray.data, function (dataPoint) {
const x = (myArray.data).shift();
console.log(myArray.data);
console.log(x);
return moment(dataPoint[0]).valueOf();
})),
['Expected'].concat(_.map(myArray.data, function (dataPoint) {
return dataPoint[1];
})),
['Actual'].concat(_.map(myArray.data, function (dataPoint) {
return dataPoint[1];
}))
],
x: 'x'
},
I can reproduce the result wanted using Array.shift()
let arr = [
["2017-09-20T16:00:00-07:00", 188.125, 0, 1],
["2017-09-20T17:00:00-07:00", 123.125, 0, 1],
["2017-09-20T18:00:00-07:00", 114.25, 0, 1],
["2017-09-20T19:00:00-07:00", 115, 0, 1],
["2017-09-20T20:00:00-07:00", 113.25, 0, 1],
["2017-09-20T21:00:00-07:00", 115.625, 0, 1],
["2017-09-20T22:00:00-07:00", 114.75, 0, 1],
["2017-09-20T23:00:00-07:00", 114, 0, 1],
["2017-09-21T00:00:00-07:00", 112.625, 0, 1],
["2017-09-21T01:00:00-07:00", 108.375, 0, 1],
["2017-09-21T02:00:00-07:00", 111.125, 0, 1]
];
console.log(arr[0]);
arr.shift();
console.log(arr[0]);
.shift() is working fine.
Problem is in your Array which is going to shift, Check whether myArray.data consists of data, Error says you are trying to shift a value from a undefined (null) object.
splice(0,1) also working fine
You can remove the first array item usingz myArray.data.splice(0, 1) but the error tells that you are trying to apply array method to undefined value. Perhaps the $scope has not received the value yet
Related
Here is the function:
function chunk(array: number[], size: number): number[][] {
return array.reduce((chunks, curr, _, arr) => {
console.log(arr.length); // -> 10 which is correct
// let len = arr.length; // -> Cannot read properties of undefined (reading 'length')
let len = chunks.length; // this works
if (len === 0 || chunks[len - 1].length === size) chunks.push([curr]);
else chunks[len - 1].push(curr);
return chunks;
}, []);
}
console.log(chunk([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 3)); // ->[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ], [ 10 ] ]
The fourth argument to reduce is the array that we're iterating over. I can log it and I get the correct result (10) see above. But when I try to use it and assign it to a variable I get an error(see above). Could someone please shed some light?
From Mozilla's page, the fourth parameter is the array that is being reduced. You should access the array variable that is already declared, but the fourth parameter works.
For example:
array.reduce((_, __, ___, arr) => {
console.log(arr.length == array.length) // true, this is the source array
});
The reason why you're getting the error is not because of the arr.length property, but rather the way you're accessing chunks.
I have this object:
728394 : {
"playersAmount" : 2,
"players" : {
"LRFe9w9MQ6hf1urjAAAB" : {
"nickname" : "spieler1",
"type" : "player1"
},
"nKUDWEd5p_FCBO4sAAAD" : {
"nickname" : "spieler2",
"type" : "player2"
},
"ghdaWSWUdg27sf4sAAAC" : {
"nickname" : "spieler3",
"type" : "spectator"
}
},
"activePlayer" : "LRFe9w9MQ6hf1urjAAAB",
"board" : [
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0]
]
}
How do I get everything of the object above except for the k/v pair "board"? is there any other way than just adding every key except the right one?
You can create a copy and then delete the unwanted key:
const copy = { ...original }
delete copy.unwantedProperty
Of course you can instead delete the property on the original if you don't care about mutating it.
(Note: if your environment doesn't support the syntax { ...original }, you can use Object.assign({}, original) instead.)
EDIT: Actually, this answer is even neater.
const { board, ...everythingButBoard } = yourObject
simple answer will be:
const copyObject = Object.assign({}, yourObject) // to make a copy of original variable
delete copyObject['keyToRemove'] // OR delete copyObject.keyToRemove
else if you want to delete from original variable:
delete yourObject['keyToRemove'] // OR delete yourObject.keyToRemove
I think you can create a new object excluding this key using a for...in
object = {
wantedKey: 'wantedValue',
wantedKey2: 'wantedValue2',
wantedKey3: 'wantedValue3',
unwantedKey: 'unwantedValue'
}
const newObject = {}
for (const key in object) {
if (key !== 'unwantedKey') newObject[key] = object[key]
}
console.log(newObject)
for more info about for...in: click here
I have a simple object with some simple arrays. I want to loop through each item in the object and check part of the array. For example, if a '0' or a '1' then do something.
var formvalidation = {
title: ['id1', 0],
categories: ['id2', 1],
price: ['id3', 1],
video: ['id4', 0],
fileTypes: ['id5', 0]
}
I've tried the following but I get the entire object in each loop.
jQuery(formvalidation).each(function(){
//Gives the entire object.
console.log();
});
It's a bit unclear what kind of processing you're trying to do with each property (see my comment requesting clarification).
The example below demonstrates how to loop through each property and extract the first and second value from the arrays you're storing. This example is meant to illustrate how to access each property and its values only - you'll obviously need to plug your logic in where appropriate.
var formvalidation = {
title: ['id1', 0],
categories: ['id2', 1],
price: ['id3', 1],
video: ['id4', 0],
fileTypes: ['id5', 0]
};
for (let prop in formvalidation) {
if (Object.prototype.hasOwnProperty.call(formvalidation, prop)) {
console.log(`Value of prop, ${prop}, is ${formvalidation[prop] [0]}:${formvalidation[prop][1]}`);
}
}
You could also use Object.keys, which is a bit cleaner:
var formvalidation = {
title: ['id1', 0],
categories: ['id2', 1],
price: ['id3', 1],
video: ['id4', 0],
fileTypes: ['id5', 0]
};
const keys = Object.keys(formvalidation)
for (const key of keys) {
console.log(formvalidation[key]);
}
Not to say that the previous answer here isn't right, but I thought Id go with what it led me to as the answer in this case.
jQuery.each(formvalidation, function(key, value){
if (value[1] == 0) {
e.preventDefault();
}
})
I was playing with ES6 array helper functions reduce() and find(). I'm trying to display array of unique elements. But it is failing in case of value 0. I'm not able to find what's wrong with my code. Please guide.
Here is my code snippet:
var arrayWithDuplicates = [0, 0, 1, 2, 3, 3, 4, 4, 'a', 'a'];
var arrayWithUniqueValues = arrayWithDuplicates
.reduce((previous, item) => {
if(!previous.find(element => element === item)) {
previous.push(item)
}
return previous;
}, []);
console.log('arrayWithUniqueValues', arrayWithUniqueValues)
I'm getting below output:
arrayWithUniqueValues [ 0, 0, 1, 2, 3, 4, 'a' ]
Why I'm getting 0 twice while all other values are unique?
You can achieve the same result by converting your array into a Set and back to an Array.
var arrayWithUniqueValues = [...new Set(arrayWithDuplicates)];
The reason your code doesn't work, by the way, is that Array.prototype.find returns the element it found. When you search for 0, it returns 0 and then !0 is true. So 0 is added even if it is already in the array. You can do instead:
if (previous.indexOf(item) === - 1) {
previous.push(item);
}
The find() method returns the value of the first element in the array that satisfies the provided testing function. Otherwise undefined is returned.
when you got 0,the code becomes :
arrayWithDuplicates.reduce(([0], 0) => {
if(!previous.find(element => element === item)) {
//![0].find(0=>0===0),return 0,so !0 means true
previous.push(item)
//so [0,0]
}
return previous;
});
a better way is
let a=[...new Set([0, 0, 1, 2, 3, 3, 4, 4, 'a', 'a'])];//[0, 1, 2, 3, 4, "a"]
I need to loop through an entire 2D array (OldTable) to check that Column1 has a value of 1 and Col7 is not empty (null). If the above conditions are true then push the current (i) arrays of elements into newTable.
My snippet of JS is as follow...
var newTable = [];
for (var i=1; i<OldTable.length; i++){
if(OldTable[i][0]==1 && OldTable[i][7]!==null){
newTable.push(OldTable[i]);
}
}
Seems like a fairly straight forward thing to do but currently hitting brick wall with this error...
TypeError: Cannot read property "0" from undefined. (line 80, file
"Code"
I have tried to reduce the if statement to just...
if(OldTable[i][0]==1){
...but still the same error.
I'm able to display the array element just fine using...
Browser.msgBox(OldTable[50][0]);
I'm fairly new to JS so could be a simple silly error someone could point out.
UPDATE: In trying to simplying naming, I've actually made it more difficult with conflicting terminology, so have going through and updated the variable names used.
Your code should work if, as noted in the comment by #Massimo, you change your loop from starting at i=1 to i=0, as shown below. Also, just to whet your appetite for more modern tools within JavaScript, I also include an essentially identical solution to the problem using ES6/ES2015.
var myArray = [
[1, 0, 0, 0, 0, 0, 0, 'foo' ], // should pass
[9, 1, 1, 1, 1, 1, 1, 'foo' ], // should fail
[1, 2, 2, 2, 2, 2, 2, 'foo' ], // should pass
[1, 3, 3, 3, 3, 3, 3, null ], // should fail
[0, 4, 4, 4, 4, 4, 4, null ], // should fail
[1, 5, 5, 5, 5, 5, 5, undefined], // should pass
[1, 6, 6, 6, 6, 6, 6, 'foo' ] // should pass
];
function f1(array) {
var newArray = [];
for (var i = 0; i < array.length; i++) {
if (array[i][0] == 1 && array[i][7] !== null) {
newArray.push(array[i]);
}
}
return newArray;
}
const f2 = array => array.filter(e => e[0] === 1 && e[7] !== null);
console.log(f1(myArray));
console.log(f2(myArray));