How to concatenate values of duplicate keys - javascript

When reading a csv into a javascript dictionary, how can I concatenate values of what would otherwise be duplicate keys? I've seen answers for how to do this with bash, c#, and perl, but I haven't been able to find answers for Javascript. Here's what I have:
var subjects = {};
d3.csv("test.csv", function(data) {
for (var i = 0; i < data.length; i++)
{
subjects[data[i].Id] = data[i].VALUE;
}
console.log(subjects);
});
This, obviously writes over existing keys. Instead, I want the key to be an array of the values. The csv basically looks like:
Id, VALUE
id1, subject1
id2, subject1
id1, subject3
And I want to output as:
{"id1": ["subject1", "subject3"], "id2": ["subject1"]...}

Just check if your output already has the key, if so you add the new value to the array. Else you create an array.
d3.csv("test.csv", function(data) {
var subjects = {};
for (var i = 0; i < data.length; i++)
{
// Check if key already exists
if(subjects.hasOwnProperty(data[i].Id)){
// push data to array
subjects[data[i].Id].push(data[i].VALUE);
}else{
// create new key and array
subjects[data[i].Id] = [data[i].VALUE];
}
}
console.log(subjects);
});

You could make it into an array and then push the content into that array
var subjects = {};
d3.csv("test.csv", function(data) {
for (var i = 0; i < data.length; i++)
{
//first time we see this id, turn it into an array
if(typeof subjects[data[i].Id] != "object"){
subjects[data[i].Id] = [];
}
//push content to the array
subjects[data[i].Id].push(data[i].VALUE);
}
console.log(subjects);
});

Try this inside the for loop:
typeof subjects[data[i].Id] == 'undefined' && (subjects[data[i].Id] = []);
subjects[data[i].Id].push(data[i].VALUE);

You can reduce the footprint of your code slightly if you use reduce:
var out = data.reduce((p, c) => {
const id = c.Id;
p[id] = p[id] || [];
p[id].push(c.VALUE);
return p;
}, {});
RESULT
{
"id1": [
"subject1",
"subject3"
],
"id2": [
"subject1"
]
}
DEMO

Related

Remove data from an array comparing it to an other array

I am trying to compare the items in "item" array and the copyofOpList array to retrieve the data occurrences in copyofOpList
this is my try:
var _deleteUsedElement1 = function(item) {
for (var i = 0; i < item.length-1; i++){
for (var j = 0; j< $scope.copyofOpList.length-1; j++){
if (item[i].operationCode == $scope.copyofOpList[j].code) {
$scope.copyofOpList.splice(j, 1);
} } } };
$scope.compareArrays = function() {
...Get data from web Service
_deleteUsedElement1(item);
}
the copyofOpList array has 14 elements,and the item array has 2 array
but my code deletes only one occurrence (the first),so please how can I correct my code,to retrieve any occurances in the copyofOpList array comparing to the item array
thanks for help
I'd try to avoid looping inside a loop - that's neither a very elegant nor a very efficient way to get the result you want.
Here's something more elegant and most likely more efficient:
var item = [1,2], copyofOpList = [1,2,3,4,5,6,7];
var _deleteUsedElement1 = function(item, copyofOpList) {
return copyofOpList.filter(function(listItem) {
return item.indexOf(listItem) === -1;
});
};
copyofOpList = _deleteUsedElement1(item, copyofOpList);
console.log(copyofOpList);
//prints [3,4,5,6,7]
}
And since I just noticed that you're comparing object properties, here's a version that filters on matching object properties:
var item = [{opCode:1},{opCode:2}],
copyofOpList = [{opCode:1},{opCode:2},{opCode:3},{opCode:4},{opCode:5},{opCode:6},{opCode:7}];
var _deleteUsedElement1 = function(item, copyofOpList) {
var iOpCodes = item.map(function (i) {return i.opCode;});
return copyofOpList.filter(function(listItem) {
return iOpCodes.indexOf(listItem.opCode) === -1;
});
};
copyofOpList = _deleteUsedElement1(item, copyofOpList);
console.log(copyofOpList);
//prints [{opCode:3},{opCode:4},{opCode:5},{opCode:6},{opCode:7}]
Another benefit of doing it in this manner is that you avoid modifying your arrays while you're still operating on them, a positive effect that both JonSG and Furhan S. mentioned in their answers.
Splicing will change your array. Use a temporary buffer array for new values like this:
var _deleteUsedElement1 = function(item) {
var _temp = [];
for (var i = 0; i < $scope.copyofOpList.length-1; i++){
for (var j = 0; j< item.length-1; j++){
if ($scope.copyofOpList[i].code != item[j].operationCode) {
_temp.push($scope.copyofOpList[j]);
}
}
}
$scope.copyofOpList = _temp;
};

Get full value from array using partial value

I have an array like this:
var array = ["xs-1", "sm-10", "md-4"];
Now I want to get the number at the end of a particular value. For example I want to search the array for "md-" and see what number is at the end of that string (should return 4).
I can't do array.indexOf("xs-") because that isn't the whole value. Is there a way to do this?
Using a for loop:
var array = ["xs-1", "sm-10", "md-4"];
var search = "md-";
var found = null;
for (var i = 0; i < array.length; i++) {
if (array[i].indexOf(search) === 0) {
found = array[i];
break; // Note: this is assuming only one match exists - or at least you are
// only interested in the first match
}
}
if (found) {
alert(found);
} else {
alert("Not found");
}
Using .filter:
var array = ["xs-1", "sm-10", "md-4"];
var search = "md-";
var filtered = array.filter(function(item) {
return item.indexOf(search) === 0;
});
// note that here filtered will contain all matched elements, so it might be more than
// one match.
alert(filtered);
Building from #János Weisz's suggestion, you can easily transform your array into an object using .reduce:
var array = ["xs-1", "sm-10", "md-4"];
var search = "md";
var obj = array.reduce(function(prev, item) {
var cells = item.split("-");
prev[cells[0]] = cells[1];
return prev;
}, {});
// note: at this point we have an object that looks like this:
// { xs:1, sm:10, md: 4 }
// if we save this object, we can do lookups much faster than looping
// through an array
// now to find "md", we simply do:
alert(obj[search]);
If you need to do multiple look ups from the same source array, then transforming it into an object may be the most efficient approach overall. You pay the initial price of the transformation, but after than lookups are O(1) versus O(n) for each time you have to search your array. Of course, if you only ever need one item, then probably don't bother.
I recommend using objects for this:
var array = [{'type': 'xs', 'value': 1}, {'type' : 'sm', 'value': '10'}, {'type' : 'md', 'value': '4'}];
This way you can search the array as:
function searchMyArrayByType(array, type) {
var items[];
for (var i = 0; i < array.length; i++)
{
if (array[i].type == type) items.push(array[i].value);
}
return items;
}
var valuesWithMd = searchMyArrayByType(array, 'md');
For more information regarding the structure and use of objects, please refer to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects
You can create a method that takes the prefix you're looking for, the array, and the split character and returns all the numbers in an array:
function findNumberFromPrefix(prefix, arr, splitChar) {
var values = [];
for (var i = 0; i < arr.length; i++) {
if (arr[i].indexOf(prefix) === 0) {
values.push(arr[i].split(splitChar)[1]);
}
}
return values;
}
And call it:
var array = ["xs-1", "sm-10", "md-4"];
var values = findNumberFromPrefix("md-", array, "-");
console.log(values); //["4"]
Demo: http://jsfiddle.net/rn4h9msh/
A more functional approach and assuming you can have have more than one element with the same prefix:
function findPrefix(array, prefix) {
return array.filter(function (a) { return a.indexOf(prefix) === 0; })
.map(function (e) { return e.slice(prefix.length); })
}
If you have only one matching element, do a loop like this:
var array = ["xs-1", "sm-10", "md-4"];
var needle = "md-";
for(i=0;i<array.length;i++) {
if(array[i].indexOf(needle) == 0)
alert(array[i].substr(needle.length, array[i].length));
}
Demo: http://jsfiddle.net/kg0c43ov/
You can do it like this...
var array = ["xs-1", "sm-10", "md-4"];
getValue("md-");
function getValue(search) {
for(var key in array) {
if(array[key].indexOf(search) > -1) {
alert("Array key is: " + key);
alert("Array value is: " + array[key].replace(search, ""));
}
}
}
JSFiddle here.

How can I find which index in an array contains an object whose value for a specific key is x? [duplicate]

I would like to find index in array. Positions in array are objects, and I want to filter on their properties. I know which keys I want to filter and their values. Problem is to get index of array which meets the criteria.
For now I made code to filter data and gives me back object data, but not index of array.
var data = [
{
"text":"one","siteid":"1","chid":"default","userid":"8","time":1374156747
},
{
"text":"two","siteid":"1","chid":"default","userid":"7","time":1374156735
}
];
var filterparams = {userid:'7', chid: 'default'};
function getIndexOfArray(thelist, props){
var pnames = _.keys(props)
return _.find(thelist, function(obj){
return _.all(pnames, function(pname){return obj[pname] == props[pname]})
})};
var check = getIndexOfArray(data, filterparams ); // Want to get '2', not key => val
Using Lo-Dash in place of underscore you can do it pretty easily with _.findIndex().
var index = _.findIndex(array, { userid: '7', chid: 'default' })
here is thefiddle hope it helps you
for(var intIndex=0;intIndex < data.length; intIndex++){
eachobj = data[intIndex];
var flag = true;
for (var k in filterparams) {
if (eachobj.hasOwnProperty(k)) {
if(eachobj[k].toString() != filterparams[k].toString()){
flag = false;
}
}
}
if(flag){
alert(intIndex);
}
}
I'm not sure, but I think that this is what you need:
var data = [{
"text":"one","siteid":"1","chid":"default","userid":"8","time":1374156747
}, {
"text":"two","siteid":"1","chid":"default","userid":"7","time":1374156735
}];
var filterparams = {userid:'7', chid: 'default'};
var index = data.indexOf( _.findWhere( data, filterparams ) );
I don't think you need underscore for that just regular ole js - hope this is what you are looking for
var data = [
{
"text":"one","siteid":"1","chid":"default","userid":"8","time":1374156747
},
{
"text":"two","siteid":"1","chid":"default","userid":"7","time":1374156735
}
];
var userid = "userid"
var filterparams = {userid:'7', chid: 'default'};
var index;
for (i=0; i < data.length; i++) {
for (prop in data[i]) {
if ((prop === userid) && (data[i]['userid'] === filterparams.userid)) {
index = i
}
}
}
alert(index);

selecting particular keys from json data

I have a array as:
var cols = ["ticker", "highPrice", "lowPrice","lastPrice"] // dynamic
Json data comming from backend as:
info = {ticker: "AAPL", marketCap: 2800000000, lowPrice: 42.72, highPrice: 42.84}
suppose I want to select market cap then I can do info.marketCap. But I want to select only those json values which keys are equals to cols i.e. info.ticker, info.highPrice, info.lowPrice
and assign N/A to those which is undefined in json but present in cols array i.e info.lastPrice = "N/A"
Note: cols changes from time to time
Here is what I have got so far
SyScreener.fillScreenerResult = function(info) {
var cols = ["ticker", "highPrice", "lowPrice", "openPrice", "lastPrice", "currentVol", "avgVol"];
var data = [];
for(var i=0; i<info.length; i++) {
var jsonKeys = Object.keys(info[i]);
for(var j=0; j<jsonKeys.length; i++) {
if(cols.contains(jsonKey[j])) {
// TODO something like - data.push([info[i].jsonKey[j])
} else {
// TODO something like - info[i].colsValue = "N/A"
}
}
}
SyUtils.createDataTable("screener_result", data);
};
do you mean something like this:
var cols = ["ticker", "highPrice", "lowPrice","lastPrice"];
info = {ticker: "AAPL", marketCap: 2800000000, lowPrice: 42.72, highPrice: 42.84};
for(var c = 0, clen = cols.length; c < clen; c++) {
if( !(cols[c] in info) ) {
console.log("N/A");
}
else {
console.log(info[cols[c]]);
}
}
Demo:: jsFiddle
I may not be reading your question correctly but from my understanding I might suggest something like this.
for (var i=0; i<cols.length; i++) {
var fieldName = cols[i];
if (!info.hasOwnProperty(fieldName)) {
info[fieldName] = 'N/A';
}
}
This simply iterates through each field name in cols and checks if it is a property of the info JSON object. If it isn't already present the loop adds the property with a value of 'N/A'.
var cols = ["ticker", "highPrice", "lowPrice","lastPrice"]
var info = {ticker: "AAPL", marketCap: 2800000000, lowPrice: 42.72, highPrice: 42.84}
var output = {};
for(each in info) {
var index = cols.indexOf(each)
if(index != -1) {
output[each] = info[each];
//remove extra already checked element
cols.splice(index,1)
}
}
//append remaining keys
for(var i=0;i<cols.length;i++) {
output[cols[i]] = "N/A"
}
console.log(output)
//output Object {ticker: "AAPL", lowPrice: 42.72, highPrice: 42.84, lastPrice: "N/A"}
First thing, you nedd deserialize you JSON data.
To do this using jQuery use the function parseJson that you can find here
http://api.jquery.com/jquery.parsejson/
once you deserialized it, you can do whatever you want with this data since you manipulate it as a plain javascript array. Hope this helps.

Want to search string in the array of objects?

I want to search this employee array which is consisted of objects and i should be able to search any text like if i pass ---> search_for_string_in_array ('aaron', employees) ; it should display me 'Value exists in array' or if its the way please help me..
//here is the employeee array ...
var employees =[{
name:"jacob",
age :23,
city:"virginia",
yoe :12,
image :'a.jpg'
},
{
name:"aaron",
age :21,
city:"virginia",
yoe :12,
image :'b.jpg'
},
{
name:"johnny",
age :50,
city:"texas",
yoe :12,
image :'c.jpg'
},
{
name:"jacob",
age :12,
city:"virginia",
yoe :12,
image :'a.jpg'
}];
here is the function which performs searching functionality inside an array.
function search_for_string_in_array(search_for_string, employees)
{
for (var i=0; i < employees.length; i++)
{
if (employees[i].match(search_for_string))
{
return 'Value exists in array';
}
}
return 'Value does NOT exist in array';
}
Simply pass the value to search for and the array to the function and it will tell you whether the string exists as a part of an array value or not.
If you know the structure of the Array, you should probably just loop through it and test each value. If you don’t know the structure, you can stringify the array into JSON and regexp it (although it won’t be as safe):
function search_for_string_in_array(str, arr) {
var json = JSON.stringify(arr);
return new RegExp(':\"'+str+'\"','g').test(json);
}
just replace the line
if (employees[i].match(search_for_string))
with this:
if (employees[i].name.match(search_for_string))
Try
function search(text) {
text += '';
var i, obj;
var array = [];
for (i = 0; i < employees.length; i++) {
var obj = employees[i];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
if (('' + obj[key]).indexOf(text) >= 0
|| ('' + key).indexOf(text) >= 0) {
array.push(obj);
break;
}
}
}
}
return array.length > 0;
}
Demo: Fiddle1 Fiddle2

Categories

Resources