4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

indexOfとspliceメソッドを使った削除方法 JavaScript 【Snippets】

Posted at

概要

JavaScriptで特定の要素を削除(配列から取り除く)方法がいくつかあるので、今回はspliceの書き方例をメモします。

MDN: splice

MDN: indexOf

コード

index.js
const userLists = [
  { id: 1, name: 'Mike' },
  { id: 2, name: 'Taro' },
  { id: 3, name: 'John' }
];

const user = userLists.find(user => user.id === 3);
// 'John'を取得

const index = userLists.indexOf(user);
// 'John'は2番目のユーザー

userLists.splice(index, 1);  
// 2番目から、1つの要素を取り除きます

console.log(userLists); 
// 残りの要素(ユーザー)は{ id: 1, name: 'Mike' }, { id: 2, name: 'Taro' }

userLists.find(user => user.id === 3)の「3」は、Node.jsでreq.params.idで「3」を取得したと想定しています。

削除するまでの流れ

これらの流れを言葉にして読み上げると、記憶に残りやすかったのでメモ。

  • 配列リストから特定の要素を取得する 例: { id: 3, name: 'John' }
  • indexOfで配列の何番目の要素か調べる。 例: name: 'John'は2番目のユーザー
  • splice(index, 1) で、index番目の要素を1つ取り除く
  • 残った要素(ユーザー)は{ id: 1, name: 'Mike' }, { id: 2, name: 'Taro' }です。
4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?