Skip to content

Instantly share code, notes, and snippets.

@emeaguiar
Created January 2, 2019 19:08
Show Gist options
  • Save emeaguiar/499ecbc4854bc6f858ddfd43009d944b to your computer and use it in GitHub Desktop.
Save emeaguiar/499ecbc4854bc6f858ddfd43009d944b to your computer and use it in GitHub Desktop.
let array = [ 'foo', 'bar', 'baz' ];
let removedElement;
// Elimina la primer instancia de 'bar'
if ( array.indexOf( 'bar' ) > -1 ) {
removedElement = array.splice( array.indexOf( 'bar' ), 1 );
}
// [ 'foo', 'baz' ]
console.log( array );
// [ 'bar' ]
console.log( removedElement );
// Reiniciar para el siguiente ejemplo
let index;
array = [ 'foo', 'bar', 'baz', 'bar' ];
// Elimina todas las instancias de 'bar'
while ( ( index = array.indexOf( 'bar' ) ) > -1 ) {
removedElement = array.splice( array.indexOf( 'bar' ), 1 );
// [ 'bar' ]
console.log( removedElement );
}
// [ 'foo', 'baz' ]
console.log( array );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment