JavaScript University continues as we develop our first utility function that will allow us to filter and retrieve only the unique values from an array. Along the way, I'll also teach you how to use the excellent Firebug to debug your code.
Utility Functions and Debugging
Final Code from the Video:
var unique = function(origArr) { var newArr = [], origLen = origArr.length, found, x, y; for ( x = 0; x < origLen; x++ ) { found = undefined; for ( y = 0; y < newArr.length; y++ ) { if ( origArr[x] === newArr[y] ) { found = true; break; } } if ( !found) newArr.push( origArr[x] ); } return newArr; }; // Test it out var myarray = ['jeffrey', 'allie', 'patty', 'damon', 'zach', 'jeffrey', 'allie']; myarray = unique(myarray); console.log(myarray); // jeffrey, allie, patty, damon, zach
Conclusion
So, with this lesson out of the way, you now know how to build your own helpful utility functions. I hope you enjoyed today's video tutorial!
Comments