4
1

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 1 year has passed since last update.

要素の抽出・削除・書き換えなどの配列操作(JavaScript)

Posted at

配列から重複した値を削除する


const fruits = ["banana", "apple", "apple", "orange", "grape", "apple"];

// fromを使う方法
const uniqueFruits = Array.from(new Set(fruits));
console.log(uniqueFruits)

// ...を使う方法
const uniqueFruits2 = [...new Set(fruits)];
console.log(uniqueFruits2)

// 共に ["banana", "apple", "orange", "grape"]

// 従来の方法(おすすめしない)
const result = fruits.filter((x, i, self) => {
  return self.indexOf(x) === i;
});
console.log(result);

Array.from詳細

new Set詳細

配列の中で特定のkey:valueだけを取得する

const friends = [
  { name: 'John', age: 22 },
  { name: 'Peter', age: 23 },
  { name: 'Mark', age: 24 },
  { name: 'Maria', age: 22 },
  { name: 'Monica', age: 21 },
  { name: 'Martha', age: 19 },
]

const friendsNames = Array.from(friends, ({name}) => name);
console.log(friendsNames);

// 従来の方法(おすすめしない)
const friendsNames = friends.map((friend) => {
	return friend.name
})
console.log(friendsNames);

配列で何らかのデータで埋めたい場合

const array1 = [1, 2, 3, 4];

// 配列のindex2~4を0で埋める
console.log(array1.fill(0, 2, 4));
// [1, 2, 0, 0]

// 配列のindex2以降を0で埋める
console.log(array1.fill(5, 2));
// [1, 2, 5, 5]

// 配列の全てを6で埋める
console.log(array1.fill(6));
// [6, 6, 6, 6]

2つの配列から共通項を抽出する

const numOne = [0, 2, 4, 6, 8, 8];
const numTwo = [1, 2, 3, 4, 5, 6];
const duplicatedValues = [...new Set(numOne)].filter(item => numTwo.includes(item));
console.log(duplicatedValues); // [2, 4, 6]

配列の中からfalsyな値を取り除く

const mixedArr = [0, "blue", "", NaN, 9, true, undefined, "white", false];
const trueArr = mixedArr.filter(Boolean);
console.log(trueArr); // returns ["blue", 9, true, "white"]

配列の中の数字を全て足す

const nums = [1, 5, 2, 6];
const sum = nums.reduce((x, y) => x + y);
console.log(sum); // 14

配列を1つのオブジェクトにする

const data = [
  { name: 'Taro', age: 20 },
  { name: 'Hanako', age: 25 },
  { name: 'Tom', age: 30 }
];

const result = data.reduce((prev, current) => {
  prev[current.name] = current.age;
  return prev;
}, {});

console.log(result); // {Taro: 20, Hanako: 25, Tom: 30}

配列を1つのindex{key:value}のオブジェクトにする

const data = [
  { name: 'Taro', age: 20 },
  { name: 'Hanako', age: 25 },
  { name: 'Tom', age: 30 }
];
const result = data.reduce((prev, current, index) => ({
...prev, [index]: current}), 
{});

console.log(result)

/* 
{
  0: {
    age: 20,
    name: "Taro"
  },
  1: {
    age: 25,
    name: "Hanako"
  },
  2: {
    age: 30,
    name: "Tom"
  }
} */

配列の中で特定のkey:valueだけを取得する

const data = [
  { id: 1, name: 'Taro', age: 20, country: 'Japan'},
  { id: 2, name: 'Yan', age: 30, country: 'China'},
  { id: 3, name: 'Bob', age: 40, country: 'America'},
];

const result = data.reduce((prev, current) => {
  const { name, country } = current;
  prev.push({ name, country });
  return prev;
}, []);

const result2 = data.map((data) => {
  return {
    name: data.name,
    country: data.country,
  }
})

console.log(result);
console.log(result2);

/* 共に
[{
  country: "Japan",
  name: "Taro"
}, {
  country: "China",
  name: "Yan"
}, {
  country: "America",
  name: "Bob"
}] */

配列の中で条件にあったものだけを抽出する

const accounts = [
  { id: 1, firstName: 'taro',    lastName: 'sato',      age: 10, sex: 'male' },
  { id: 2, firstName: 'jiro',    lastName: 'suzuki',    age: 28, sex: 'male' },
  { id: 3, firstName: 'saburo',  lastName: 'takahashi', age: 19, sex: 'male' },
  { id: 4, firstName: 'hanako',  lastName: 'tanaka',    age: 10, sex: 'female' },
  { id: 5, firstName: 'sachiko', lastName: 'kobayashi', age: 20, sex: 'female' }
];

// accounts をもとにして、未成年男性のフルネームを配列で取得したい
// 期待する結果 ["taro sato", "saburo takahashi"]

const result= accounts.filter(data => data.age < 20 && data.sex === 'male')
  .map(data => `${data.firstName} ${data.lastName}`);
  console.log(result)

参考記事

https://qiita.com/rana_kualu/items/24e5b6009ad831102db4
https://kde.hateblo.jp/entry/2018/10/13/065738#配列をオブジェクトにする
https://chaika.hatenablog.com/entry/2019/05/07/083000
https://ics.media/entry/200825/

4
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?