Skip to content

Instantly share code, notes, and snippets.

@tkd55
Last active November 6, 2019 10:40
Show Gist options
  • Save tkd55/dd96340d6e3082304e888c8ed29a367c to your computer and use it in GitHub Desktop.
Save tkd55/dd96340d6e3082304e888c8ed29a367c to your computer and use it in GitHub Desktop.
tips

オブジェクトの配列で重複した要素を削除する

const distinctArray = array => {
  const cleanList = array.filter((value1, index, array) => {
    // findIndex : 同じ要素があればそのインデックスを返す
    // nameの値が同じもののインデックスと全体のインデックスが同じものだけ抽出
    return array.findIndex(value2 => value1.name === value2.name) === index;
  });

  return cleanList;
};

const users = [
  { name: 'tkd1', age: 18 },
  { name: 'tkd2', age: 20 },
  { name: 'tkd3', age: 22 },
  { name: 'tkd2', age: 25 },
  { name: 'tkd3', age: 26 }
];

const distinctUsers = distinctArray(users);
console.log(distinctUsers); // [  { name: 'tkd1', age: 18 },{ name: 'tkd2', age: 20 },{ name: 'tkd3', age: 22 },]

時間でSort

const sortByTime = (array: any) => {
  return array.sort((a: any, b: any) => {
    if (a.time < b.time) return -1
    if (a.time > b.time) return 1
    return 0
  })
}

const fruits = [ { orange: 100, apple: 120 }, { orange: 120, apple: 180 }, { orange: 130, apple: 240 }, { orange: 140, apple: 120 }, { orange: 150, apple: 180 } ];

合計

const total = fruits.reduce((acc, currentValue) => {
  return acc + currentValue.orange;
}, 0);
console.log(total);

最大値 / 最小値

const users = [
  { name: 'tkd1', age: 18 },
  { name: 'tkd2', age: 20 },
  { name: 'tkd3', age: 22 },
  { name: 'tkd2', age: 25 },
  { name: 'tkd3', age: 26 }
];

// 最大
const maxAgeUser = users.reduce((acc, currentValue, index) =>
  acc.age > currentValue.age ? acc : currentValue
);
console.log(maxAgeUser);

// 最小値
const minAgeUser = users.reduce((acc, currentValue, index) =>
  acc.age < currentValue.age ? acc : currentValue
);
console.log(minAgeUser);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment