Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Essential Vanilla JavaScript Functions
Amit Merchant
Amit Merchant

Posted on

     

Essential Vanilla JavaScript Functions

Essential Vanilla JavaScript Functions

Some of the missing functions in JavaScript in vanilla form (inspired byPHP). You can just try it as a programming practice.

Array Functions

array_unique()

Remove duplicates from an array

functionarray_unique(arr){varseen={};varret_arr=[];varkey;vari;functionkeyify(obj){varret="";varj;if(Object.prototype.toString.call(obj)==="[object Object]"||Object.prototype.toString.call(obj)==="[object Array]"){for(jinobj){ret+="~"+j+"^"+keyify(obj[j])+"%";}returnret;}else{returnobj;}}for(i=0;i<arr.length;i++){key=keyify(arr[i]);if(!(keyinseen)){ret_arr.push(arr[i]);seen[key]=true;}}returnret_arr;}array_unique([4,5,4,6,7,8,2,6]);// [4, 5, 6, 7, 8, 2]array_unique([{a:'val'},{b:'val',c:'val'},'a','b',[1,2,3,4],{a:'val'},[1,2,3,4],[{a:'val'},{b:'val'}],[{a:'val'},{b:'val'}]]);// [{a: 'val'}, {b: 'val', c: 'val'}, 'a', 'b', [1,2,3,4], [{a: 'val'}, {b: 'val'}]]
Enter fullscreen modeExit fullscreen mode

array_merge()

Merge two arrays

functionarray_merge(arr1,arr2){for(vari=0;i<arr2.length;i++){arr1.push(arr2[i]);}returnarr1;}array_merge([1,2,3],[4,5]);// [1, 2, 3, 4, 5]
Enter fullscreen modeExit fullscreen mode

array_chunk()

Splits an array into chunks of arrays

functionarray_chunk(arr,count){vartemp_arr=[];for(vari=0;i<arr.length;){varchunk_arr=[];for(varj=0;j<count;j++){if(!arr[i])break;chunk_arr.push(arr[i]);i++;}temp_arr.push(chunk_arr);}returntemp_arr;}array_chunk([1,2,3,4,5,6,7,8,9],4);// [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9 ] ]
Enter fullscreen modeExit fullscreen mode

array_collapse()

Collapses a collection of arrays into a single, flat array

functionarray_collapse(...arrays){varcollapse_arr=[];for(vari=0;i<arrays.length;i++){for(varj=0;j<arrays[i].length;j++){collapse_arr.push(arrays[i][j]);}}returncollapse_arr;}array_collapse([1,2,3,4],[5,6],["hello","world"]);// [ 1, 2, 3, 4, 5, 6, 'hello', 'world' ]
Enter fullscreen modeExit fullscreen mode

array_diff()

Returns the values in thearr1 that are not present inarr2

functionarray_diff(arr1,arr2){vartemp_arr=[];for(vari=0;i<arr1.length;i++){if(arr2.indexOf(arr1[i])==-1){temp_arr.push(arr1[i]);}}returntemp_arr;}array_diff([4,5,6,7,"unicorn"],[5,6,7]);// [ 4, 'unicorn' ]
Enter fullscreen modeExit fullscreen mode

array_intersect()

Returns the values common in the two supplied arrays

functionarray_intersect(arr1,arr2){vartemp_arr=[];for(vari=0;i<arr1.length;i++){if(arr2.indexOf(arr1[i])!=-1){temp_arr.push(arr1[i]);}}returntemp_arr;}array_intersect([4,5,6,7,"unicorn"],[5,6,7,8]);// [ 5, 6, 7 ]
Enter fullscreen modeExit fullscreen mode

array_map()

Sends each value of an array to a user-made function, which returns new values

functionarray_map(arr,func){vartemp_arr=[];if(typeoffunc!=="function")throw"Second parameter should be a function";for(vari=0;i<arr.length;i++){temp_arr.push(func(arr[i]));}returntemp_arr;}array_map([1,2,3,4,5],function(value){returnvalue*2;});// [ 2, 4, 6, 8, 10 ]
Enter fullscreen modeExit fullscreen mode

array_reject()

Filters the array using the given callback. The callback should returntrue if the item should be removed from the resulting array

functionarray_reject(arr,func){vartemp_arr=[];if(typeoffunc!=="function")throw"Second parameter should be a function";for(vari=0;i<arr.length;i++){if(func(arr[i]))temp_arr.push(arr[i]);}returntemp_arr;}array_reject([1,2,3,4,5],function(value){returnvalue>3;});// [ 4, 5 ]
Enter fullscreen modeExit fullscreen mode

array_split()

Breaks an array into the given number of groups

functionarray_split(arr,count){vartemp_arr=[];vararr_length=arr.length;varchunk=Math.floor(arr_length/count);for(vari=0;i<arr.length;){varchunk_arr=[];if(temp_arr.length==(count-1))chunk=chunk+(arr_length-i);for(varj=0;j<chunk;j++){if(!arr[i])break;chunk_arr.push(arr[i]);i++;}temp_arr.push(chunk_arr);}returntemp_arr;}array_split([1,2,3,4,5,6,7,8,9],4);// [ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ], [ 7, 8, 9 ] ]
Enter fullscreen modeExit fullscreen mode

array_take()

Returns a new array with the specified number of items

functionarray_take(arr,count){vartemp_arr=[];if(count<0){count=Math.abs(count);for(vari=(arr.length-count);i<arr.length;i++){temp_arr.push(arr[i]);}}else{for(vari=0;i<count;i++){temp_arr.push(arr[i]);}}returntemp_arr;}array_take([1,2,3,4,5,6,7,8,9],4);// [ 1, 2, 3, 4 ]
Enter fullscreen modeExit fullscreen mode

You may also pass a negative integer to take the specified amount of items from the end of the array:

array_take([1,2,3,4,5,6,7,8,9],-3);// [ 7, 8, 9 ]
Enter fullscreen modeExit fullscreen mode

array_pad()

Inserts a specified number of items, with a specified value, to an array

functionarray_pad(arr,size,value){for(vari=0;i<size;i++){arr.push(value);}returnarr;}array_pad([1,2,3,4],2,"unicorn");// [ 1, 2, 3, 4, 'unicorn', 'unicorn' ]
Enter fullscreen modeExit fullscreen mode

range()

Creates an array containing a range of elements

functionrange(start,end){vartemp_arr=[];for(vari=start;i<=end;i++){temp_arr.push(i);}returntemp_arr;}range(5,11);// [ 5, 6, 7, 8, 9, 10, 11 ]
Enter fullscreen modeExit fullscreen mode

String Functions

chunk_split()

Splits a string into a series of smaller parts

functionchunk_split(string,length,end){vartemp_string='';for(vari=0;i<string.length;i++){temp_string+=string[i];if((i+1)%length==0)temp_string+=end;}returntemp_string;}console.log(chunk_split("Hello",1,"."));// H.e.l.l.o.console.log(chunk_split("Hello",1,".."));// H..e..l..l..o..
Enter fullscreen modeExit fullscreen mode

str_pad()

Pads a string to a new length

functionstr_pad(string,size,value){for(vari=0;i<size;i++){string+=value;}returnstring;}str_pad("unicorn",5,".");// unicorn.....
Enter fullscreen modeExit fullscreen mode

strrev()

Reverses a string

functionstrrev(string){vartemp_string='';for(vari=string.length-1;i>=0;i--){temp_string+=string[i];}returntemp_string;}strrev("unicorn");// nrocinu
Enter fullscreen modeExit fullscreen mode

similar_text()

Calculates the similarity between two strings

functionsimilar_text(string1,string2){varseen={};varsimilar_count=0;for(vari=0;i<string1.length;i++){if((string2.indexOf(string1[i])!==-1&&!(string1[i]inseen))||string1[i]==''){similar_count++;if(string1[i]!='')seen[string1[i]]=true;}}returnsimilar_count;}similar_text("Hello World","Hello Peter");// 6
Enter fullscreen modeExit fullscreen mode

Originally published atamitmerchant1990/essential-vanilla-javascript-functions.

Top comments(13)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
lexlohr profile image
Alex Lohr
...former musician, voice actor, martial artist, started coding 38 years ago and turned front-end developer 25+ years ago.

Interesting approach for array_unique (even taking into account that objects and arrays in the array might have different pointers, but have the same content. There's just one minor issue:x in y will also return true for the constructor attribute, so better usey.hasOwnProperty(x). If your array contains'constructor' as a string, your function will filter it out.

CollapseExpand
 
amit_merchant profile image
Amit Merchant
Coder, thinker and an aspiring entrepreneur.
  • Location
    India
  • Work
    Software Engineer
  • Joined

Yeah. We can implement it that way as well. If you want you can send over a pull request ongithub.com/amitmerchant1990/essent...

CollapseExpand
 
lexlohr profile image
Alex Lohr
...former musician, voice actor, martial artist, started coding 38 years ago and turned front-end developer 25+ years ago.

There you go.

CollapseExpand
 
rehia profile image
Jérôme Avoustin
  • Joined

Sorry, but while the big majority of these functions are pretty useless (you might find them in lodash or even in the language itself), the implementations show a big misunderstanding of how JavaScript works.
You can do pretty much anything with Array functions likemap,reduce,filter,slice andconcat. They are helpful because they do not mutate the original array, but produce a new one.
And finally, it is really not necessary to pollute your code with such ugly names, even if PHP provides them. Next readers won't necessary know a lot about PHP.

CollapseExpand
 
eerk profile image
eerk
Creative technologist, lecturer at University for Applied sciences.Interests: Typescript, Machine Learning, React, Arduino, Front-end, CSS
  • Location
    Rotterdam
  • Education
    Bachelor of Arts
  • Work
    Lecturer
  • Joined

This, and you can even use the ...spread operator instead of concat, to create a new array from an existing one.
The above functions are translated a bit too literally from PHP, or perhaps the intention was to make them work for ES5 / lower?

CollapseExpand
 
hoffmann profile image
Peter Hoffmann
Father, Full Stack Developer, World Savior
  • Location
    Jena, TH, Germany
  • Education
    Diplom Physik
  • Work
    IT boy at Friedrich-Schiller-Universität Jena, Projekt kompetenztest.de
  • Joined

Why aremap,reject andtaken part of your list (they already exist in vanilla JS)? When (besides an job interview) did you have the need forstrrev?
Besides that a very nice exercise.

CollapseExpand
 
amit_merchant profile image
Amit Merchant
Coder, thinker and an aspiring entrepreneur.
  • Location
    India
  • Work
    Software Engineer
  • Joined
• Edited on• Edited

Pardon me for that. I was curious and was just trying to do my implementation.

CollapseExpand
 
weswedding profile image
Weston Wedding
  • Joined

Gotta give a shout out toLocutus here, a source for hundreds of Javascript implementations of PHP functions (and other languages).

CollapseExpand
 
meisekimiu profile image
Natalie Martin
  • Work
    Software Engineer
  • Joined

Neat! I love doing things in Vanilla JavaScript over including a big library whenever I can. However, to make the code a bit nicer I'd suggest adding the array and string methods to their actual object prototypes if possible. In my opinion it makes the code look much nicer and is a convenience Javascript has the original PHP functions do not. (That's the reason PHP has so many functions that start with "array" or "string")

CollapseExpand
 
tobbwiz profile image
Bernard Sibanda
Full Stack developer. Founder of Tobb Technologies.
  • Location
    South Africa
  • Joined

I love what you have done. Keep it up. The raised point on mutation is a good one. These need to process cloned objects not original. With regard these (map, reduce, filter, slice and concat), blind use of these is as good as blind use of frameworks.

CollapseExpand
 
gcdcoder profile image
Gustavo Castillo
I'm a web developer I won't fix your computer >:(
• Edited on• Edited

Awesome utilities, just one question, what is this line for?

ret += "~" + j + "^" + keyify(obj[j]) + "%";

Why do you use "~", ^ and "%"?

CollapseExpand
 
gregorgonzalez profile image
Gregor Gonzalez
  • Joined

Yes! This is exactly what I needed. As a PHP developer I always use those functions. Thank you.

CollapseExpand
 
ryanhaber profile image
Ryan Haber
I make things hard things easy.
  • Email
  • Location
    Washington, D.C.
  • Education
    Loyola University Maryland
  • Work
    Technical Product Manager at Enovational
  • Joined

Fun. Thanks!

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Coder, thinker and an aspiring entrepreneur.
  • Location
    India
  • Work
    Software Engineer
  • Joined

More fromAmit Merchant

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp