alphabetically sort a hash table in javascript - javascript

I am trying to sort a hashtable (originally called "resultVal") alphabetically in javascript.
// initializing an array with all the keys. //
var keys = [];
// populating it with all the keys in the hashtable. //
for (var key in resultVal) {
if (resultVal.hasOwnProperty(key)) {
keys.push(key);
}
}
// Alphabetically sorting the array populated with hash table keys. //
keys.sort();
var temp = {};
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var value = resultVal[key];
if (key != "") {
temp[key].push(value);
}
}
My issue is with the last statement :-
temp[key].push(value);
What I am doing is, sort the keys alphabetically and re-feed the key and its respective values into a temp hashtable..."temp".
The push statement isn't being recognized. can anyone help?

temp is defined as an object, not an array. There's no need to push() onto it:
temp[key] = value;

Related

Javascript array keys loop through checking

There is an array that contains key value pairs which the key will contain a manipulative id. The problems is that I intend to achieve a concept of checking the key values which is if the key is exist in the array, then the value will check; or else it will create a new key value pairs for the new and unique id. I looked for the Object.keys() function and i find out it will only return array of keys. I tend to check the keys one by one in a for loop tho.
sorry if I did not explain my question well
code:
var marks = new Array();
function totalScore(critId,score){
var compare = Object.keys(marks);
var result = 0;
for(var i = 0; i < marks.length; i++){ //Looping in marks array
for(var j = 0; j < compare.length; j++){ //Looping in compare array
if(compare[j] == marks[i]){ //Comparing the key of the arrays
marks[i] = score; //If matched update the value of the current key
result ++;
}
}
if(result == 0){ //If there are no result of the comparison
marks.critId = score; //Add new key value pair to the array
}
}
}
If I understand your problem correctly, you want to add a new key/value pairs if it doesn't exist.
It's better to use an object or an ES6 Map for this case.
var marks = {};
function totalScore(critId, score) {
if(!(critId in marks)) marks[critId] = score;
}
totalScore(1, 5);
totalScore(2, 8);
totalScore(1, 4);
console.log('marks', marks);

why Object.keys(data).sort() not work as expected?

I am trying to sort my object keys.
But when I'm printing my object, it always print bb first. Can anyone explain this?
It should print aa first ? I already sorted my keys.
My first key should be aa and then second should be bb.
Here is my code
var data = {
bb:"bb",
aa:"cc"
};
Object
.keys(data)
.sort();
console.log(data)
DEMO
Two things:
objects in JS have no order of elements, like arrays do
Object.keys returns an array of object keys, it does not modify the object itself, see the following example:
var data={bb:"bb",aa:"cc"};
var arr = Object.keys(data);
arr.sort();
console.log(arr); // the array IS modified,
// but it has nothing to do with the original object
try this
var data={bb:"bb",aa:"cc"};
var keys = Object.keys(data);
keys.sort();
var obj = {};
for(i = 0; i < keys.length; i++){
obj[keys[i]] = data[keys[i]];
}
console.log(obj);
There is not any method for sorting object keys in JavaScript but you can do this by a object prototype like this.
Object.prototype.sortKeys = function () {
var sorted = {},
key, a = [];
for (key in this) {
if (this.hasOwnProperty(key)) {
a.push(key);
}
}
a.sort();
for (key = 0; key < a.length; key++) {
sorted[a[key]] = this[a[key]];
}
return sorted;
}
var data = {bb: "bb", aa :"cc"};
alert(JSON.stringify(data.sortKeys())); // Returns sorted object data by their keys

Generate multi dimensional array with key value in javascript

I have an array from json like this:
{"1001":"Account1","1002":"Account2","1003":"Account3"}
and i need convert it to key value format:
[{id:"1001",name:"Account1"},
{id:"1002",name:"Account2"},
{id:"1003",name:"Account3"}]
To do this i wrote this function:
function arrayToMultiArray(list) {
var matrix = [], i;
i = -1;
for (var key in list) {
i++;
matrix[i] = [];
matrix[i].push({"id":key, "name":list[key]});
}
return matrix;
}
but the generated array has brackets for each array
[[{id:"1001",name:"Account1"}],
[{id:"1002",name:"Account2"}],
[{id:"1003",name:"Account3"}]]
How can i remove brackets of internal arrays?
You added array in array.
Just change
i++;
matrix[i] = [];
matrix[i].push({"id":key, "name":list[key]});
to
matrix.push({"id":key, "name":list[key]});
you are creating a multidimensional array.
remove this
i++;
matrix[i] = [];
and do this directly
matrix.push({"id":key, "name":list[key]});
You could do the same with Object.keys and Array.prototype.map
var obj = {"1001":"Account1","1002":"Account2","1003":"Account3"};
var arr = Object.keys(obj).map(function(key) {
return { id : key, name : obj[key] }
});
console.log(arr);

Delete JSON items based on array of allowed items

I have an array of allowedFields based on the names of the keys from a JSON array generated from a form.
A number of the retrieved fields are not required at this stage and therefore should not go through the validation process, therefore I want to match the values of the JSON array with the values of the allowedFields array
Returned JSON from form
{"reference":"sdfsdfsdfsd",
"start_date":"04/22/2014",
"end_date":"05//2014",
"status":"1","frequency":"M",
"day":"sat",
"contract_type":"S",
"notice_period":"1M"}
allowedFields = array(
reference,
start_date,
end_date,
contract_type
)
Basically I need to strip out any fields that are not listed in the allowedFields javascript array
1) Parse the JSON to an object.
var obj = JSON.parse(json);
2) Ensure that you've defined your array correctly.
var allowedFields = ['reference','start_date','end_date','contract_type'];
3) Loop over the object and if the key is not in the array delete it.
for (var k in obj) {
if (allowedFields.indexOf(k) < 0) delete obj[k];
}
4) Stringify your object back to JSON.
var str = JSON.stringify(obj);
Output
{"reference":"sdfsdfsdfsd","start_date":"04/22/2014","end_date":"05//2014","contract_type":"S"}
Fiddle
var all = {"reference":"sdfsdfsdfsd",
"status":"1"};
var allowedFields = ['reference']; // note quote marks to create strings
function filter(data, allowed) {
var filtered = {};
for(var id=0; id < allowed.length; ++id) {
var allowedField = allowed[id];
if(data.hasOwnProperty(allowedField)) {
filtered[allowedField] = data[allowedField];
}
}
return filtered;
}
console.log(filter(all, allowedFields));
>> [object Object] {
>> reference: "sdfsdfsdfsd"
>> }
Demo
underscore.js solution:
_.pick(obj,allowedFields)
http://underscorejs.org/#pick
demo
There is also _.omit(obj,string|string[]) that does the opposite.
underscore.js is extremely useful and I use it quite a bit, but you can also pick just the tools you need and include those in your code. The library is quite optimized and there is no need to write your own.
Here is the implementation (from here)
_.pick = function(obj, iterator, context) {
var result = {};
if (_.isFunction(iterator)) {
for (var key in obj) {
var value = obj[key];
if (iterator.call(context, value, key, obj)) result[key] = value;
}
} else {
var keys = concat.apply([], slice.call(arguments, 1));
for (var i = 0, length = keys.length; i < length; i++) {
var key = keys[i];
if (key in obj) result[key] = obj[key];
}
}
return result;
};

JavaScript: convert objects to array of objects

I have thousands of legacy code that stores array information in a non array.
For example:
container.object1 = someobject;
container.object2 = someotherobject;
container.object3 = anotherone;
What I want to have is:
container.objects[1], container.objects[2], container.objects[3] etc.
The 'object' part of the name is constant. The number part is the position it should be in the array.
How do I do this?
Assuming that object1, object2, etc... are sequential (like an array), then you can just iterate through the container object and find all the sequential objectN properties that exist and add them to an array and stop the loop when one is missing.
container.objects = []; // init empty array
var i = 1;
while (container["object" + i]) {
container.objects.push(container["object" + i]);
i++;
}
If you want the first item object1 to be in the [1] spot instead of the more typical [0] spot in the array, then you need to put an empty object into the array's zeroth slot to start with since your example doesn't have an object0 item.
container.objects = [{}]; // init array with first item empty as an empty object
var i = 1;
while (container["object" + i]) {
container.objects.push(container["object" + i]);
i++;
}
An alternate way to do this is by using keys.
var unsorted = objectwithobjects;
var keys = Object.keys(unsorted);
var items = [];
for (var j=0; j < keys.length; j++) {
items[j] = unsorted[keys[j]];
}
You can add an if-statement to check if a key contains 'object' and only add an element to your entry in that case (if 'objectwithobjects' contains other keys you don't want).
That is pretty easy:
var c = { objects: [] };
for (var o in container) {
var n = o.match(/^object(\d+)$/);
if (n) c.objects[n[1]] = container[o];
}
Now c is your new container object, where c.object[1] == container.object1

Categories

Resources