Removing duplicates from a JavaScript object array

Removing duplicates from a JavaScript array is an often encountered problem but after searching around, I have found very few good solutions to this. I wrote a small program but I realized that my solution had a O(n2) complexity. So I asked on twitter if someone knew of a better solution:

http://twitter.com/#!/vikasrao/status/77134502132064256

My friend pointed out that I can use a map. Since a JavaScript object is essentially a map. I came up with:

var arr = [
    { name: "a", age: 24},
    { name: "b", age: 25},
    { name: "a", age: 24},
    { name: "b", age: 25}
];

var newarr = [];
var unique = {};

dojo.forEach(arr, function(item) {
    if (!unique[item.age]) {
        newarr.push(item);
        unique[item.age] = item;
    }
});

console.log(dojo.toJson(newarr)); //prints [{"name":"a","age":24},{"name":"b","age":25}]

Here’s a JsFiddle link for the above code: http://jsfiddle.net/k6v3R/1/

I’m sure there are better solutions out there, but the complexity for the above code is O(n) although I’m thinking I don’t need to use both an object and an array to filter unique items.

JavaScript’s call and apply methods

A lot of people starting out with JavaScript are unsure of how JavaScript’s call() and apply() methods work. Some have a theoretical understanding of it but are not sure where they would use these powerful methods. I’m taking a stab below at explaining them:

Call and Apply are JavaScript methods used to pass the required object scope for a function to execute as expected.

The syntax for the JavaScript call method:

fun.call(object, arg1, arg2, ...)

The syntax for the JavaScript apply method:

fun.apply(object, [argsArray])

The main difference is that call() accepts an argument list, while apply() accepts a single array of arguments.

So if you want to call a function which prints something and pass an object scope for it to execute in, you can do:

function printSomething() {
    console.log(this);
}
printSomething.apply(new SomeObject(),[]); // empty arguments array
// OR
printSomething.call(new SomeObject()); // no arguments

Here’s a JsFiddle example below which explains how scope can be passed as required: http://jsfiddle.net/8uRXe/8/

The first alert window uses the scope of the dojo widget, while the second call without any scope passed to it uses the default window scope for the “this” object printed from the printSomething() method.

Dojo provides a hitch method which allows the programmer to pass around scope. This hitch method along with dojo.connect is probably what I love most about Dojo.

  var myObj = {
        foo: "bar"
    };
    var func = dojo.hitch(myObj, function() {
        console.log(this.foo);
    });
    func();

Here’s a small example continuing the earlier examples: http://jsfiddle.net/8uRXe/9/

Hopefully this sheds some light on these 2 powerful JavaScript methods.

Validate email address using JavaScript

In order to validate email address using JavaScript, use this simple check:

//where emailString is the string under consideration
if(/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{3}$/.test(emailString)) {
 console.log("valid email address");
}

Breakdown of : /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{3}$

  • First part checks for alpha numberic characters, period, underscore and – are allowed.
  • Needs to have an @ sign
  • Last part can only contain 3 characters (a-z or A-Z) alphabets only, if you want anywhere between 2-4 characters, you can use {2,4} instead of {3} like I have.

UPDATE:
This below should work just as well as the above regex. For more useful info, check this out.

(/^[/\w/._-]+@[/\w/.-]+\.[a-zA-Z]{3}$/.test("vikas123@gmail.com"))

The above code in action here

Sorting birthdays received from Facebook’s graph API

While working with Friend lists using Facebook’s graph API, you may want to retrieve your friends and do something based on their birthdays. Here’s some sample code to sort your friends based on upcoming birthdays.

FB.api("/me/friends?fields=id,name,birthday,picture, link", dojo.hitch(this, function(response) {
    var birthdays = response.data; //list of friend objects from facebook
    var currentMonth = new Date().getMonth() + 1;
    var upcoming = [];
    dojo.forEach(birthdays, function(item) {
        if (item.birthday) {
            var bday = item.birthday;
            //if the birthday is after today
            if (currentMonth <= bday.substr(0, 2) * 1 && new Date().getDate() <= new Date(bday).getDate()) {
                upcoming.push(item);
            }
        }
    });

    //set the year to current year because of birth years being different.
    var year = new Date().getFullYear();
    upcoming = upcoming.sort(function(a, b) {
        return new Date(a.birthday).setYear(year) - new Date(b.birthday).setYear(year);
    });

    console.log(upcoming);//console log here, but do whatever you want with the sorted friends
}));

Webdirections unplugged 2011 summary

I spent the last 2 weekdays of this week at the Webdirections Unplugged 2011 conference in Seattle. My visit was sponsored by 2 sources: a free raffle ticket paid for by the Bay Area Mobile Meetup group and the trip expenses paid for by my company.
A brief overview of the conference and the sessions:

The conference was pretty small, about 200-250 people in all I’d say. The conference wifi was great as a result. So was the food and the after-party on Thursday.

The sponsor booths were not that great as compared to other places I’ve been to, but the Blackberry people were giving away lot of free stuff. However, its hard to get someone excited about Blackberry gear huh? I even won a free blackberry phone! 🙂

However, I was there to get some learning value out of the whole thing, so here’s a rundown of the sessions I attended:

Thursday morning:

1. Keynote address by Chris Wilson from Google called “The interconnectedness of all things”

2. Testing and debugging apps – by Ross Boucher – really useful talk with information on debugging. He highly recommended Web Inspector for debugging, so I’ll be using it a lot more
over the next few days to help debug code. He also mentioned that the other major takeaway from his talk was Charles proxy, which I have not heard of, so I’ll be spending some time with that as well. Great talk overall.
Slides here.

3. Nicholas Zakas – Web speed bumps – Slides here.
This talk had some really good suggestions on how to improve performance such as embedding images in CSS files using Data URIs, etc.

4. HTML5 for game building – by Robby Ingebretsen and Kevin Moore – They explained their development journey in building their very very cool HTML5 game called Agent 8 ball. I spent quite a bit of time the rest of the day playing their game.

5. Mobile Prototyping essentials – by Rachel Hinman – I sat through the talk but I found that it was not very relevant for what I work with.

Friday Morning:

1. Friday started off with a roundtable discussion where people could choose the topics they wanted to discuss.
I chatted with a fun group for an hour about HTML5 game building.

2. CSS3 animations and transitions – Stephanie Rewis – I liked this talk, also great material on her website in the resources section.

3. Offline web apps with HTML5 – Dave Orchard – mainly to do with offline storage, very insightful talk, but it was quite technical so I’m looking forward to the slides so that I can through them again to refresh my memory.

4. HTML5 Graphics, Canvas deep dive – Dave Balmer – Slides here. I liked this talk. I also had the pleasure of chatting with the speaker and lending him my macbook charger while we were outside waiting in the lobby. Turns out that apart from liking JavaScript, we both also like the Thai place called Sweet Basil in Foster City, CA :).
I later found out he’s done a lot more with JavaScript than I have. Respect. I now follow him on Twitter.

That was it, after this talk, there was a closing talk, where they announced winners for the Blackberry tablet and phones. They handed out 10 phones, of which I got one :).

I flew out the next day back to the Bay Area, after being subjected to a random security check at the Seattle airport. Wonderful. And it rained in San Francisco when I landed. Such is life :).

Common array operations in JavaScript

Programmers, no matter what language they work with always need to work with Arrays. I primarily work with JavaScript and its Dojo library. So here’s a few useful methods to do the common array operations using Dojo/JavaScript:

1. Add an element to the array.


var arr = ["gold", "silver"];
arr.push("platinum");
//prints ["gold", "silver", "platinum"]

2. Remove an element from the array.

arr.pop();
//pops "platinum"

Adding and removing elements given an element’s index is best done using JavaScript’s splice() method. Look at the next 2 operations below, adding and removing an element.

3. Add an element from the array given its index.


var arr = ["gold", "silver"];
var removed = arr.splice(1, 0, "platinum");
console.log(arr);
//prints ["gold", "platinum", "silver"] because item "platinum" has been added at index 1.

4. Remove an element from the array given its index.


var arr = ["gold", "silver", "platinium"];

//remove item at index 1 (second argument is 1, which means remove)
var removed = arr.splice(1, 1); 
console.log(arr);
//prints ["gold", "platinum"] because item "silver" at index 1 has been removed.

Dojo provides some very cool array helper methods as well.

5. Perform an operation on every element of the array.


var arrSalary = [200, 300, 1500, 5, 4500];

// for every element in the array, increment by 10 %.

arrSalary = dojo.map(arrSalary, function(item) {
            return item + (item / 100) * 10;
        });

console.log(arrSalary);

//prints [220, 330, 1650, 5.5, 4950] 

6. Filter the contents of an array based on a certain condition


var arrSalary = [200, 300, 1500, 5, 4500];

//filter array elements greater than 300. 
arrSalary = dojo.filter(arrSalary, function(item) {
    return item >=300;
});

console.log(arrSalary);

//prints [300, 1500, 4500] 

7. To iterate over an array, dojo provides a easy to use method called dojo.forEach.

dojo.forEach(arr, function(item, i) {
  //do something with each item.
});

8. Remove duplicates from an array.

var arr = [1,2,3,4,1,6,7,2,7,4];
var newarr = [];
dojo.forEach(arr, function(item, i) {
 if(dojo.indexOf(newarr, item)  == -1) {
  newarr.push(item);
 }
});

console.log(newarr);

These are functions I use on a very regular basis, so I thought I’d write them down and share.

Playing with Dates in Dojo

To convert a ISOString into a Date object, use dojo.date.stamp.fromISOString. For example:

var dateObj = dojo.date.stamp.fromISOString("2011-04-26T19:30:40+0000"))

To convert a Date object into a localized date format which you would like, 3 parameters I regularly tend to use are “selector” and “formatLength” and “datePattern”:

dojo.date.locale.format( dateObj, {selector:'date', formatLength:'full'} )
//returns  "Tuesday, April 26, 2011"

You can also specify different datePatterns like datePattern: “yyyyMMdd”, etc. More details here.

A useful link for confirming to regular cultural conventions here.

RSS feed using JavaScript – Cont’d

JsonDuit turned out to be a failed experiment, mainly because they insist on linking to the feed “widget” created on their website.
What I was looking for was a way to make a cross domain request which would fetch the RSS XML and I could parse it. Turns out solution 3 from my earlier post was the way to go. To implement this is extremely simple. First include the yui file:

       http://yui.yahooapis.com/3.3.0/build/yui/yui-min.js

Once this is done, its easy to use it anywhere in the project:

YUI().use('yql', function(Y) {
Y.YQL('select title from rss where url="https://vikasrao.wordpress.com/feed/"', function(r) {
  var items = r.query.results.item;
  dojo.forEach(items, function(data){
    //do something                        
  });
});

To experiment with YQL queries, use the YQL console here.

Reading RSS feed using JavaScript

I have an idea in mind to build a simple introductory website for myself and one of the things I wanted on the front page of that website was a RSS feed type of thing on the front page. This way I could link to this existing blog link and not have to deal with moving my blog to a new domain, etc.

Anyway, surprisingly, few solutions exist to read a blog’s feed(which is XML) and do things with it using JavaScript.

Things I tried:

1. Looked at WordPress to see if it provided a JavaScript API. It doesn’t.

2. Since I use Dojo for all my JavaScript programming, I looked at dojo.script.io.get to make a cross domain Ajax call and then use the response to extract what I want out of the feed.
Turns out dojo.script.io.get only can handle JSON responses. So this fails as a solution.

3. YUI combined with YQL is a possible solution. I could use YQL to query the feed and then use YUI to read that result. Not bad. Definitely a solution.

4. Then I found JSonduit. Seems to be written just to solve my problem 🙂 How does this work?

You include this JS file:

And then, call the following function:

JSonduit.feed.load(feedId, 0, function(data) {
if (data.error) {
alert("Feed Error: " + data.error.error + " : " + data.error.desc);
}
else {
//do something with the result
}
});

Read up here for more information about this and some sample code.

2010 in review

The stats helper monkeys at WordPress.com mulled over how this blog did in 2010, and here’s a high level summary of its overall blog health:

Healthy blog!

The Blog-Health-o-Meter™ reads This blog is on fire!.

Crunchy numbers

Featured image

A helper monkey made this abstract painting, inspired by your stats.

This blog was viewed about 9,600 times in 2010.

The busiest day of the year was May 6th with 234 views. The most popular post that day was JSF 2.0, Session Beans and JPA using Scala.

Where did they come from?

The top referring sites in 2010 were dzone.com, jsfcentral.com, en.wordpress.com, google.com, and blogs.sourceallies.com.

Some visitors came searching, mostly for javascript interview questions, scala jpa, scala ant, scala jsf, and jpa scala.

Attractions in 2010

These are the posts and pages that got the most views in 2010.

1

JSF 2.0, Session Beans and JPA using Scala May 2010
1 comment

2

Commonly asked JavaScript interview questions February 2010
2 comments

3

Scala with JPA February 2009
8 comments

4

Ant for Scala! June 2009
3 comments

5

JSF with scala managed beans January 2009
6 comments

Look forward to more posts this year 🙂