I have a list with duplicate elements,I need to use velocity
For Example, posts contains duplicate elements
#foreach ($p in $posts)
$p.name //will be unique
#end
I want to remove the duplicate using velocity,
Any help would be appreciated
This is possible, and this should work depending on your version of velocity. A bit more concise than the answer above.
#set($uniquePosts = [])
#foreach($post in $posts)
#if( ! $uniquePosts.contains( $post.name ) )
#if( $uniquePosts.add($post.name) ) #end
##note the if above is to trap a "true" return - may not be required
$post.name
#end
#end
Just for the sake of argument because others said it is not possible with Velocity, I wanted to show that it is actually possible with Velocity, but still not recommended.
For those who are interested how it could be done:
#set($uniquePosts = [])
#foreach($post in $posts)
#set($exists = false)
#foreach($uniquePost in $uniquePosts)
#if($uniquePost.name == $post.name)
#set($exists = true)
#break
#end
#end
#if(!$exists)
#set($added = $uniquePosts.add($post))
#end
#set($posts = $uniquePosts)
#end
Unique list:
#foreach($post in $posts)
$post.name
#end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With