0
0

More than 1 year has passed since last update.

【JavaScript】便利な配列操作テクニック集

Last updated at Posted at 2021-10-02

配列内の要素を一意にする

  const arr = ["A", "A", "B", "C", "C", "C", "B", "D"];
  // eleは要素
  // iはindex
  // selfはarr配列
  // indexOfは配列内から引数で指定した値が最初に現れたindexを返す
  const newArr = arr.filter((ele, i, self) => self.indexOf(ele) === i);
  console.log(newArr); // => ["A", "B", "C", "D"]

2つの配列を組み合わせた処理

const func = () => {
  //targetのnameプロパティに一致したarrはidとセットの配列にする

  const arr = ["佐藤", "鈴木","トマト"];

  const target = [
    {
      id: 0,
      name: "佐藤"
    },
    {
      id: 1,
      name: "田中"
    },
    {
      id: 2,
      name: "鈴木"
    }
  ];

  const result = arr.map((ele) => {
    let targetId = "";
    target.forEach((obj) => {
      if (obj.name === ele) {
        targetId = obj.id;
      }
    });
    return targetId === "" ? { name: ele } : { id: targetId, name: ele };
  });
  console.log(result); // => [ { id:0, name:"佐藤" }, { id:2, name:"鈴木" }, { name:"トマト" } ]
};
0
0
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
0
0