107
97

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.

配列から要素を探す

Posted at

javascriptにも配列の便利なメソッドがあるので備忘録

##find(配列から対象の要素を探す)

find.js
const cityList = [
    { name: '東京', value: '1' },
    { name: '神奈川', value: '2' },
    { name: '千葉', value: '3' },
    { name: '埼玉', value: '4' },
];

const target = cityList.find((city) => {
    return (city.name === '東京');
});

console.log(target); // { name: '東京', value: '1' }

##filter(配列から任意の条件のものだけ取得する)

filter.js
const cityList = [
    { country: '日本', name: '東京', value: '1' },
    { country: '日本', name: '神奈川', value: '2' },
    { country: '日本', name: '千葉', value: '3' },
    { country: '日本', name: '埼玉', value: '4' },
    { country: 'アメリカ', name: 'ワシントン', value: '5' },
    { country: 'イギリス', name: 'ロンドン', value: '6' },
    { country: 'フランス', name: 'パリ', value: '7' },
];

const targetList = cityList.filter((city) => {
    return (city.country === '日本');
});

console.log(targetList); 
// [
//     { country: '日本', name: '東京', value: '1' },
//     { country: '日本', name: '神奈川', value: '2' },
//     { country: '日本', name: '千葉', value: '3' },
//     { country: '日本', name: '埼玉', value: '4' }
// ]
107
97
1

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
107
97

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?