Search Lessons, Code Snippets, and Videos
search by algolia
X
#native_cta# #native_desc# Sponsored by #native_company#

Angular Pipe to Shuffle Strings With JavaScript

written by Jeff Delaney
full courses and content on fireship.io

In this quick snippet, I provide code to randomly shuffle a string with JavaScript. It works by breaking down the string into an array, shuffling it, then joining it back together. This might be useful for hiding content or anonymizing data.

You could also use the lodash shuffle operator to replace the randomize function defined below.

text shuffled with JavaScript

shuffle.pipe.ts

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
name: 'shuffle'
})
export class ShufflePipe implements PipeTransform {

transform(value: string): string {
if (!value) return ''
return value.split('').sort(this.randomize).join('')
}

private randomize(a, b) {
return Math.random()>.5 ? -1 : 1;
}
}

foo.component.html

<div *ngFor="let user of users | async">
{{ user.username | shuffle }}
</div>