删除重复的数组值然后存储它们[反应]

时间:2016-05-13 19:28:48

标签: javascript reactjs

我正在尝试从当前数组中删除重复的数组值。我想将新的列表(没有重复的列表)存储到一个新变量中。

var startDatePlusNinetyDays = new Date(+convertedStartDate + 24 * 3600000 * 90)

如何删除重复的名称并将非重复名称放入新变量?

ie:uniqueNames将返回...

var names = ["Daniel","Lucas","Gwen","Henry","Jasper","Lucas","Daniel"];

const uniqueNames = [];
const namesArr = names.filter((val, id) => {
    names.indexOf(val) == id;  // this just returns true
});

(我正在使用react jsx)谢谢!

5 个答案:

答案 0 :(得分:16)

你可以用单行

来完成
const uniqueNames = Array.from(new Set(names));

//它将返回一组唯一项

请注意@Wild Widow指出了你的一个错误 - 你没有使用return语句。 (当我们忘记时,它会很糟糕,但它会发生!)

我将补充一点,如果你考虑过滤器(a,b,c)函数的第三个参数,你的代码可以简化并且回调可以更加可重用 - 其中c是被遍历的数组。有了这个说你可以重构你的代码如下:

const uniqueNames = names.filter((val, id, array) => {
   return array.indexOf(val) == id;  
});

另外,如果你使用es6

,你甚至不需要一个return语句
const uniqueNames = names.filter((val,id,array) => array.indexOf(val) == id);

答案 1 :(得分:1)

您忘记在return电话

中使用filter语句
const namesArr = duplicatesArray.filter(function(elem, pos) {
    return duplicatesArray.indexOf(elem) == pos;
}); 

答案 2 :(得分:1)

如果要删除包含相同“ id”的重复值,则可以使用它。

const arr = [
  { id: 2, name: "sumit" },
  { id: 1, name: "amit" },
  { id: 3, name: "rahul" },
  { id: 4, name: "jay" },
  { id: 2, name: "ra one" },
  { id: 3, name: "alex" },
  { id: 1, name: "devid" },
  { id: 7, name: "sam" },
  ];

function getUnique(arr, index) {

  const unique = arr
       .map(e => e[index])

       // store the keys of the unique objects
       .map((e, i, final) => final.indexOf(e) === i && i)

       // eliminate the dead keys & store unique objects
      .filter(e => arr[e]).map(e => arr[e]);      

   return unique;
}

console.log(getUnique(arr,'id'))

结果:

> Array 
[ 
  { id: 2, name: "sumit" },
  { id: 1, name: "amit" },
  { id: 3, name: "rahul" },  
  { id: 4, name: "jay" },  
  { id: 7, name: "sam" }
]

答案 3 :(得分:0)

由于我发现@Infaz的答案的代码在某处使用并且使我感到困惑,所以我想我应该共享重构的功能。

function getUnique(array, key) {
  if (typeof key !== 'function') {
    const property = key;
    key = function(item) { return item[property]; };
  }
  return Array.from(array.reduce(function(map, item) {
    const k = key(item);
    if (!map.has(k)) map.set(k, item);
    return map;
  }, new Map()).values());
}

// Example
const items = [
  { id: 2, name: "sumit" },
  { id: 1, name: "amit" },
  { id: 3, name: "rahul" },
  { id: 4, name: "jay" },
  { id: 2, name: "ra one" },
  { id: 3, name: "alex" },
  { id: 1, name: "devid" },
  { id: 7, name: "sam" },
];
console.log(getUnique(items, 'id'));
/*Output:
[ 
  { id: 2, name: "sumit" },
  { id: 1, name: "amit" },
  { id: 3, name: "rahul" },  
  { id: 4, name: "jay" },  
  { id: 7, name: "sam" }
]
*/

答案 4 :(得分:0)

你也可以这样做

{Array.from(new Set(yourArray.map((j) => j.location))).map((location) => (
          <option value={`${location}`}>{location}</option>
        ))}
相关问题