Here is a simple data set
data = [
{'artist':'a','song':'a'},
{'artist':'a','song':'b'},
{'artist':'a','song':'c'},
{'artist':'b','song':'d'},
{'artist':'b','song':'e'},
{'artist':'c','song':'f'},
{'artist':'d','song':'g'},
{'artist':'d','song':'h'},
{'artist':'d','song':'i'}
];
Is there any native function in javascript or jQuery that would allow me to get the number of disctinct artist in a concise expression ?
To get the number of distinct artists you can use this:
Object.keys(data.reduce(function(p, c) { p[c.artist] = 1 ; return p }, {})).length
this being a one liner that accumulates the distinct values of c.artist in the object p, then counts how many keys there are.
You may try like this:
var array = [{"artist":"a","song":"a"}, {"artist":"a","song":"b"}, {"artist":"a","song":"c"}]
var unique = {};
var distinct = [];
for( var i in array ){
if( typeof(unique[array[i].song]) == "undefined"){
distinct.push(array[i].song);
}
unique[array[i].song] = 0;
}
var d = document.getElementById("d");
d.innerHTML = "" + distinct;
JSFIDDLE DEMO
try this, DEMO here
data = [
{'artist':'a','song':'a'},
{'artist':'a','song':'b'},
{'artist':'a','song':'c'},
{'artist':'b','song':'d'},
{'artist':'b','song':'e'},
{'artist':'c','song':'f'},
{'artist':'d','song':'g'},
{'artist':'d','song':'h'},
{'artist':'d','song':'i'}
];
newdata=[];
$.each(data, function(index,value){
newdata[index]=data[index].artist;
});
alert($.unique(newdata));
In my below code Im am not able to fetch data within array
var str = "Service1|USER_ID, Service1|PASSWORD"
var str_array = str.split(',');
console.log(str_array)
for(var i = 0; i < str_array.length; i++)
{
str_array[i] = str_array[i].split('|');
}
console.log(str_array)
This is the response from above code
/* [ [ 'Service1', 'USER_ID' ],
[ 'Service1', 'PASSWORD' ] ]*/
I want response to be in two different array like below
var array1 = ['Service1']
var array2 = ['USER_ID','PASSWORD']
Any help on this will be really helpful
Since you're on Node, you can do this:
var str = "Service1|USER_ID, Service1|PASSWORD";
var result = str.split(',').reduce(function(collected,splitByComma){
var splitData = splitByComma.split('|');
var key = splitData[0].replace(/\s+/gi,''); //Might want to improve this "trim"
var data = splitData[1];
if(!collected.hasOwnProperty(key)) collected[key] = [];
collected[key].push(data);
return collected;
},{});
console.log(JSON.stringify(result)); //{"Service1":["USER_ID","PASSWORD"]}
//result.Service1[0] == USER_ID
//result.Service1[1] == PASSWORD
It's not wise to place stuff in separate places. You could have them under an object key though. If service name is variable, then you could do:
var serviceName = "Service1";
result[serviceName][0] == USER_ID
result[serviceName][1] == PASSWORD
As I have understand your question, you will want an array associated with each service key, to be able to do
services.service1
and get ['username', 'password' ] ?
If so, here's a solution:
var str = "Service1|USER_ID, Service1|PASSWORD".replace(', ', ',').split(','), //[ 'Service1|USER_ID', 'Service1|PASSWORD' ]
out = {};
str.forEach(function(element){
var key, value;
element = element.split('|');
key = element[0].trim();
value = element[1].trim();
out[key] = out[key] || []; // ensures we can push the value into an array
out[key].push(value);
});
console.log(out); //{ Service1: [ 'USER_ID', 'PASSWORD' ] }
We can have a simple Regex solution
var res = "Service1|USER_ID, Service1|PASSWORD".split(/[\|,]/g);
var ar1 = [], ar2 = [];
res.forEach(function(em,i){
if(i%2==0) {
if(ar1.indexOf(em.trim())<0){
ar1.push(em.trim());
}
} else {
ar2.push(em.trim());
}
});
//ar1 and ar2 will contain expected results
This question already has answers here:
How to put items into grouped arrays where grouped by a particular key
(3 answers)
Closed 9 years ago.
I have a parent object. I want to create child objects from the parent with the same key value pair.
e.g.
parentJSON = {[name:"a1",address:"b1",comp:"c1"],
[name:"a2",address:"b2",comp:"c1"],
[name:"a3",address:"b3",comp:"c2"],
[name:"a4",address:"b4",comp:"c2"],
[name:"a5",address:"b5",comp:"c2"],
[name:"a6",address:"b6",comp:"c3"]}
Now I want to create child objects having same "comp" value.
e.g.
childJSON1 = {[name:"a1",address:"b1",comp:"c1"],
[name:"a2",address:"b2",comp:"c1"]}
childJSON2 = {[name:"a3",address:"b3",comp:"c2"],
[name:"a4",address:"b4",comp:"c2"],
[name:"a5",address:"b5",comp:"c2"]}
childJSON3 = {[name:"a6",address:"b6",comp:"c3"]}
This is what I tried to make it little bit (it will change the parent object with a key indicating number of repetition):
parentJSON = [1,2,3,3,4,4,4,5];
var i=0, x, count, item;
while(i < parentJSON.length) {
count = 1;
item = parentJSON[i];
x = i+1;
while(x < parentJSON.length &&
(x = parentJSON.indexOf(item, x)) != -1) {
count += 1;
parentJSON.splice(x,1);
}
parentJSON[i] = new Array(parentJSON[i],count);
++i;
}
console.log(parentJSON);`
first of all your json is in the incorrect format, it should look like this
[{name:"a1",address:"b1",comp:"c1"},
{name:"a2",address:"b2",comp:"c1"},
{name:"a3",address:"b3",comp:"c2"},
{name:"a4",address:"b4",comp:"c2"},
{name:"a5",address:"b5",comp:"c2"},
{name:"a6",address:"b6",comp:"c3"}]
An array of objects.
My attempt, also very readable.
var result = {};
$.each(parentJSON, function (i, item) {
if(!result[item.comp]) {
result[item.comp] = [];
}
(result[item.comp]).push(item);
});
alert(JSON.stringify(result))
JsFiddle
First of all your json is actually invalid. You may have an array of objects, but not object which contains an array like that. Also your arrays looks more like objects, because the syntax with the dots is used for objects. Here is how I guess should look like:
var parentJSON = [
[{name:"a1",address:"b1",comp:"c1"}],
[{name:"a2",address:"b2",comp:"c1"}],
[{name:"a3",address:"b3",comp:"c2"}],
[{name:"a4",address:"b4",comp:"c2"}],
[{name:"a5",address:"b5",comp:"c2"}],
[{name:"a6",address:"b6",comp:"c3"}]
];
var child1 = parentJSON.slice(0, 2);
var child2 = parentJSON.slice(2, 5);
And you may use the .slice method to get specific elements of the array.
So..you need to clone objects?
maybe tou can try sth like this:
var sergi= {
name: "sergi",
age: 33
};
var bill = (JSON.parse(JSON.stringify(sergi)));
bill.name = "Bill";
console.log(sergi);
console.log(bill);
parentJSON = function(){
return [
{name:"a1",address:"b1",comp:"c1"},
{name:"a2",address:"b2",comp:"c1"},
{name:"a3",address:"b3",comp:"c2"},
{name:"a4",address:"b4",comp:"c2"},
{name:"a5",address:"b5",comp:"c2"},
{name:"a6",address:"b6",comp:"c3"}
];
}
childJSON1 = new parentJSON().slice(0,2);
childJSON2 = new parentJSON().slice(2,5);
childJSON3 = new parentJSON().slice(5,6);
Try this:
DEMO
var data = [
[{name:"a1",address:"b1",comp:"c1"}],
[{name:"a2",address:"b2",comp:"c1"}],
[{name:"a3",address:"b3",comp:"c2"}],
[{name:"a4",address:"b4",comp:"c2"}],
[{name:"a5",address:"b5",comp:"c2"}],
[{name:"a6",address:"b6",comp:"c3"}]
];
var groups = {};
$.each(data, function(i, item) {
var comp = item.comp;
delete item.comp;
if(groups[comp]) {
groups[comp].push(item);
} else {
groups[comp] = [item];
}
});
var result = $.map(data, function(group, key) {
var obj = {};
obj[key] = group;
return obj;
});
alert(JSON.stringify(groups))
I have been able to use all the methods for automating iphone app test except with ones which returns array... e.g elements()
I have tried to do it using declaration of array as
var arr = [];
var arr = UIATarget.localTarget().frontMostApp().mainWindow().tabBar().elements();
UIALogger.logPass("result"+ arr[0]) // just to get first element
But it is not working
Can someone ans how to handle array. What is the correcting required?
What exactly do you want from such array?
Here is an example how to handle array of elements:
function getAllNamesInList (list, index){
var elem_list = list[index].elements();
var elem_count = elem_list .length;
var names = [];
var elem_name;
for (var elem_ind = 0; elem_ind < elem_count ; elem_ind++){
elem_name= elem_list [cell_ind].name();
if (!elem_name){fail ("TEST_INFO: Empty Element name!!!");}
names.push(elem_name);
}
return names;
};
Here is usage example of this function():
Your case:
var app = UIATarget.localTarget().frontMostApp();
var window = app.mainWindow();
var arr = window.tabBar()
var current_names = [];
current_names = getAllNamesInList (arr , 0);
UIALogger.logMessage ("Here are ALL names from array " + current_names );
Other possible lists which can be transferred and used within this function():
var table_views = window.tableViews();
var tab_bar = app.tabBar();
var nav_bar = app.navigationBar();
imagine you have the following JSON:
{"zero":{"0":"foo","1":"foo2"},"one":"fooa","two":"foob"}
What is the most efficient way to convert it to :
var zero = ['foo','foo2'];
var one = 'fooa';
var two = 'foob';
JSON.parse:
var json = '{"zero":{"0":"foo","1":"foo2"},"one":"fooa","two":"foob"}';
var pJson = JSON.parse(json);
var zero = [ pJson.zero[0], pJson.zero[1] ];
var one = pJson.one;
var two = pJson.two;