How to perform “Sorting, Joining or joining with some symbol” actions on all array elements by using Underscore.js function _.invoke()

When we need to perform certain actions like sorting, joining, joining with some symbol, then we can use this underscore function to easily achieve all this actions.

The _.invoke() function is used to perform certain actions like sorting, joining, joining with some symbol, make upper case etc the elements of an array. It call the function directly by its name in it’s argument list. The mentioned function will be applied on all the array elements.

Syntax:
_.invoke( list, methodName, *arguments )

Parameters:This function accepts three parameters as mentioned above and described below:

  • List: This parameter is used to hold the list of data.
  • MethodName: This parameter is used to hold the test condition.
  • Arguments: This parameter needs to add some symbols between elements.

Return values: This function returns the list formed after the given function is applied on it. 

Passing the sort() function to the _.invoke() function: The ._invoke() function takes the element from the list one by one and do the specified function on the elements. The sort function will sort the list in ascending order. The output will contain a list of all the sorted lists.

EXAMPLE:
<html>
	<head>
		<title>_.invoke() function</title>
		<script type="text/javascript" src=
		"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" >
		</script>
		<script type="text/javascript" src=
		"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore.js">
		</script>
	</head>	
	<body>
		<script type="text/javascript">
			console.log(_.invoke([[1, 6, 8],
									[7, 5, 3],
									[33, 76, 55]],
									'sort'));
		</script>
	</body>
</html>

Leave a comment

Your email address will not be published. Required fields are marked *