Using unshift function with multidimensional array - javascript

I have been trying to use the unshift function with a MD array, and I cannot get it to work accordingly.
I am using shift okay and it does what is needed like expected but unshift does not.
Below is the array which I am using:
[ [ '487', 'RINGING' ], [ '477', 'RINGING' ] ]
When I try and do an unshift on it it displays the following:
[ [ '487', 'RINGING' ], [ '477', 'RINGING' ], 2 ]
I simply need to move 477 array to the beginning like so:
[ [ '477', 'RINGING' ], [ '487', 'RINGING' ]]
The code I am using:
var channelArrStatus = [ [ '477', 'RINGING' ], [ '487', 'RINGING' ]];
function monitor_channel(event, channel) {
if (event.device_state['state'] === "RINGING") {
var name = "User_487";
var status = "NOT_INUSE"
var index = 0;
if (channelArrStatus.length === 0) {
var chanar = new Array(name, status);
channelArrStatus.push(chanar);
} else {
var found = false;
for (var i in channelArrStatus) {
var channelArrStatusElem = channelArrStatus[i];
if (channelArrStatusElem[0] === name) {
index = i;
found = true;
if (channelArrStatus[index][1] !== "DND") {
channelArrStatus.push(channelArrStatus.unshift());
setTimeout(function () {
channelArrStatus[index][1] = status;
}, 10000);
}
}
}
}
}
I cant get it to move an array to the beginning of the array as highlight above using unshift.
Any suggestions?
EDIT:JSFiddle

The call .unshift() prepends nothing and returns the length of the array - 2 in your case - and that's the value you are pushing.
You either want
channelArrStatus.push(channelArrStatus.shift()); // no un-
or
channelArrStatus.unshift(channelArrStatus.pop());
That said, you should use literal notation instead of the Array constructor and avoid for in enumerations on arrays.

On this line
channelArrStatus.push(channelArrStatus.unshift());
You are adding the length of array to the end of the array.
If you want to add an element to the start of array, just call unshift.
channelArrStatus.unshift(element);

Related

Compare 2 JSON (Array of objects)

Example structure of the JSON :
{ "array_name1" : [
{"name":"John","age":"18","group":"user","country":"UK","hobby":"series","sport":"football"},
{"name":"Ted","age":"20","group":"user","country":"US"}, ...]}
{ "array_name2" : [
{"name":"John","age":"18","group":"admin","country":"UK","hobby":"series","sport":"football"},
{"name":"Ted","age":"20","group":"user","country":"US", sport:"tennis"},
{"name":"David","age":"20","group":"user", sport:"tennis"},...]}
{ "array_name3" : [
{"name":"John","age":"18","group":"admin","country":"UK","hobby":"series","sport":"football"},
{"name":"David","age":"20","group":"user", sport:"tennis"},...]}
I have to compare 2 JSON Array of objects.
I need to compare objects with the same names in the 2 differents array of objects.
For example, I need to compare the array_name1 and array_name2 and I need to detect that a new object appeared in the array_name2. Also I need to detect that the value changed for group on John from user to admin.
If I need to compare the array_name2 and array_name3, I need to detect that the user Ted has been deleted on the array_name3.
Try like this..
var com = { "array_name1" : [
{"name":"John","age":"18","group":"user","country":"UK","hobby":"series","sport":"football"},
{"name":"Ted","age":"20","group":"user","country":"US"}]};
var com1 = { "array_name2" : [
{"name":"John","age":"18","group":"admin","country":"UK","hobby":"series","sport":"football"},
{"name":"Ted","age":"20","group":"user","country":"US", "sport":"tennis"},
{"name":"David","age":"20","group":"user", "sport":"tennis"}]}
var com2 = { "array_name3" : [
{"name":"John","age":"18","group":"admin","country":"UK","hobby":"series","sport":"football"},
{"name":"David","age":"20","group":"user", "sport":"tennis"}]};
var com3 = { "array_name3" : [
{"name":"John","age":"18","group":"admin","country":"UK","hobby":"series","sport":"football"},
{"name":"David","age":"20","group":"user", "sport":"tennis"}]};
console.log(com.array_name1 === com1.array_name2); // direct compare
function checkEqual(x,y) {
return JSON.stringify(x) === JSON.stringify(y);
}
console.log(checkEqual(com.array_name1, com1.array_name2));
console.log(checkEqual(com3.array_name3, com2.array_name3));

Filter an array by value in nested arrays

I want to return the values of array if its values contains a specific string
var names= [
["FCFEDA", "Moon Glow"],
["FCFFE7", "China Ivory"],
["FCFFF9", "Ceramic"],
["FD0E35", "Torch Green"],
["FD5B78", "Wild Watermelon"],
["FD7B33", "Crusta Green"]
];
var color_swatches = [];
var result = $.grep(names, function(v,i) {
if(v[1].indexOf("Green") > -1){
return v[0];
}
})
color_swatches.push(result);
alert(color_swatches);
results in
FD0E35, Torch Green,FD7B33, Crusta Green
I want exactly like this
["#FD0E35","#FD7B33"]
Take note that the result should inside the square brackets and with qoutes. Only contains hex not the equivalent name and # added.
Any ideas?
You could try something like this.
var names= [
["FCFEDA", "Moon Glow"],
["FCFFE7", "China Ivory"],
["FCFFF9", "Ceramic"],
["FD0E35", "Torch Green"],
["FD5B78", "Wild Watermelon"],
["FD7B33", "Crusta Green"]
];
var color_swatches = [];
names.forEach(item => {
if(item[1].indexOf("Green") > -1){
color_swatches.push('#' + item[0]);
}
});
console.log(color_swatches);
console.log(JSON.stringify(color_swatches));
The .grep() function «Finds the elements of an array which satisfy a filter function» reference
In other words, in your code it returns the "sub-array" into result.
Try using a simple loop like this:
var names= [
["FCFEDA", "Moon Glow"],
["FCFFE7", "China Ivory"],
["FCFFF9", "Ceramic"],
["FD0E35", "Torch Green"],
["FD5B78", "Wild Watermelon"],
["FD7B33", "Crusta Green"]
];
var color_swatches = [];
for(i=0;i<names.length;i++){
if(names[i][1].indexOf("Green") > -1){
color_swatches.push( names[i][0] );
}
}
//color_swatches.push(result);
console.log(JSON.stringify(color_swatches));
Notice that I used JSON.strignify() only to see the content of the color_swatches array in console.
You could use a map function to transform the color_swatches array. In the map function, you can pick the first item and add a #. Before the alert, add:
color_swatches = $.map(color_swatches[0], function(index, color_swatch) {
return "#" + color_swatch[0];
});
You can use the JavaScript functions Array#filter, Array#map and String#includes:
var names = [
["FCFEDA", "Moon Glow"],
["FCFFE7", "China Ivory"],
["FCFFF9", "Ceramic"],
["FD0E35", "Torch Green"],
["FD5B78", "Wild Watermelon"],
["FD7B33", "Crusta Green"]
]
console.log(names.filter(n => n[1].includes('Green')).map(n => `#${n[0]}`))
// ["#FD0E35","#FD7B33"]

Javascript turns array into string

I'm rewriting some Python code in javascript and I'm running into something strange. I'm sure I'm overlooking something stupid, but it appears that it's returning a comma-separated string where I expect an array.
python:
triples = [('one', 'two', 'three'), (...), ... ]
for w1, w2, w3 in triples:
key = (w1, w2)
if key in self.cache:
self.cache[key].append(w3)
else:
self.cache[key] = [w3]
returns:
('of', 'Thee,'): ['Sailing', 'Light'],
('meat', 'within'): ['is'],
javascript:
for (var i=0; i<=triples.length; i++) {
if (triples[i]) {
var key = [triples[i][0], triples[i][1]];
if (key in this.cache) {
this.cache[key].push(triples[i][2]);
} else {
this.cache[key] = [];
this.cache[key].push(triples[i][2]);
}
}
}
returns:
'you,estimated,': [ 'and', 'and' ],
'estimated,,and': [ 'far', 'far' ],

convert json string to csv using javascript

I have seen some of the posts for converting json to csv
for example 'http://jsfiddle.net/FLR4v/'.
I could not make them to convert this json to csv .
Here is my code (this works well but does not work with commented out var json3 below)
<html>
<head>
<title>JSON to CSV</title>
<script src="json.js" type="text/javascript"></script>
<script type="text/javascript">
//var json3 = { "inp1:val1": { "data": [ [ 1378267200000, 0.0743 ], [ 1378270800000, 0.1787 ] ] }}
var json3 = { "data": [ [ 1378267200000, 0.0743 ], [ 1378270800000, 0.1787 ], ] }
DownloadJSON2CSV(json3.data);
function DownloadJSON2CSV(objArray)
{
var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
var str = '';
for (var i = 0; i < array.length; i++) {
var line = '';
for (var index in array[i]) {
line += array[i][index] + ',';
}
// Here is an example where you would wrap the values in double quotes
// for (var index in array[i]) {
// line += '"' + array[i][index] + '",';
// }
line.slice(0,line.Length-1);
str += line + '\r\n';
}
window.open( "data:text/csv;charset=utf-8," + escape(str))
}
</script>
</head>
<body>
<h1>This page does nothing....</h1>
</body>
</html>
The above code works ok.
What I need is the above needs to work with the below
var json3 = { "inp1:val1": { "data": [ [ 1378267200000, 0.0743 ], [ 1378270800000, 0.1787 ] ] }}
Thanks for your help
You still haven't explained clearly what your desired output is ("CSV" is too vague, especially when your original jsfiddle produced semicolon separated output).
But you do seem to be saying that your code works if you take this object:
var json3 = { "data": [ [ 1378267200000, 0.0743 ], [ 1378270800000, 0.1787 ], ] }
...as input to your function as follows:
DownloadJSON2CSV(json3.data);
But now you want to deal with an input object that has a slightly different structure, essentially the same thing but with an extra "wrapping" layer around your original structure:
var json3 = { "inp1:val1": { "data": [ [ 1378267200000, 0.0743 ], [ 1378270800000, 0.1787 ] ] }}
If I've summed up your question accurately, here's what you need:
DownloadJSON2CSV(json3["inp1:val1"].data);
This calls your function passing the array of arrays referenced by the "data" property of the object referenced by the "inp1:val1" property of the outermost object.
(Note that what you are calling "json" is not json at all, it is an object that happens to be created using JS's object literal syntax.)
Homework for you: read the MDN article Working With Objects.

IE 8 Array iteration

Hi I'm debugging my page for IE8 compat mode, and this script just doesn't like to work and crushes.
Basically it had to iterate through a 3D array, and add a local path to a variable. Well I could do it otherwise, but I'm just curious why the ** it never works...
Any suggestions are welcome :) Here's the code:
for(i=0;i<menu_items_p.length;i++)
for(j=0;j<menu_items_p[i].length;j++)
menu_items_p[i][j][1]='http://127.0.0.1/'+menu_items_p[i][j][1];
and the array looks something like this:
var menu_items_p =
[
[ //Products
['Health Care', 'products/health.php'],
['Aroma Therapy','products/scents.php'],
],
[ // Empty
],
[ //Test
['What ever', 'spirulina/about.php'],
]
]
The problem though is that it sometimes have empty values, and array.length triggers some error...
When used your original array declaration:
var menu_items_p =
[
[ //Products
['Health Care', 'products/health.php'],
['Aroma Therapy','products/scents.php'],
],
[ // Empty
],
[ //Test
['What ever', 'spirulina/about.php'],
]
]
error occurs in IE8 but not in IE9. Just remove two commas:
var menu_items_p =
[
[ //Products
['Health Care', 'products/health.php'],
['Aroma Therapy','products/scents.php'] // here comma removed
],
[ // Empty
],
[ //Test
['What ever', 'spirulina/about.php'] // here comma removed
]
]
and all must work fine.
Maybe your code could handle empty values this way:
for(var i = 0; i < menu_items_p.length; i++) {
// we skip the value if it is empty or an empty array
if(!menu_items_p[i] || !menu_items_p[i].length) continue;
for(var j = 0; j < menu_items_p[i].length; j++) {
// again, we skip the value if it is empty or an empty array
if(!menu_items_p[i][j] || !menu_items_p[i][j].length) continue;
menu_items_p[i][j][1] = 'http://127.0.0.1/' + menu_items_p[i][j][1];
}
}
AS suggested by Yoshi and ThiefMaster, I made it following, and this is what solved it:
for(var i=0;i<menu_items_p.length;i++)
if (menu_items_p[i] !== undefined)
for(var j=0;j<menu_items_p[i].length;j++)
if (menu_items_p[i][j] !== undefined)
menu_items_p[i][j][1]='http://127.0.0.1/'+menu_items_p[i][j][1];
Global vars replaced.
Check for undefined.
It's a pity they didn't answer in a formal way, so I would have to answer my self :)
Thanks everyone!

Categories