删除数组中所有具有相同值的键

时间:2019-05-21 17:07:33

标签: javascript

我需要删除除最后插入的所有键之外的所有键,这些键在数组中的键id_ask上具有相同的值,但是我正在学习JavaScript,但我仍然不知道该怎么做。

jQuery(function()
{
    let arr = []
    let q = []
    $("body").on('click', '.link_resposta', function(event)
    {
        event.preventDefault();
        /* Act on the event */

        let id_poll = $(this).data("idpesquisa")
        let id_ask = $(this).data("idpergunta")
        let id_anwser = $(this).children("li").data("idresposta")
        let q = {
            id_poll, 
            id_ask, 
            id_anwser
        }

        arr.push(q)

        console.log(arr)
    });
});

enter image description here

1 个答案:

答案 0 :(得分:2)

使用SetArray.reverse()Array.map的组合,我们可以轻松解决此问题。

我们首先使用Set,然后将我们的源数组map放入id_ask字段中。由此,我们得到了一组唯一的id_ask

然后我们map唯一的id_ask数组,对于每个id_ask,我们在find()中的源数组上调用reverse

内联评论。

const sampleArray = [
  {
    id: 1,
    id_ask: 2,
    id_answer: 3
  },
  {
    id: 2,
    id_ask: 2,
    id_answer: 5
  },
    {
    id: 3,
    id_ask: 3,
    id_answer: 3
  },
    {
    id: 4,
    id_ask: 3,
    id_answer: 1
  },
    {
    id: 5,
    id_ask: 4,
    id_answer: 3
  }
];

// Create a unique Set of Ask ID               
const uniqueAskId = [...new Set(sampleArray.map(e => e.id_ask))]; 
console.log(uniqueAskId);

// Use Map and Reverse to get last item.
const r = uniqueAskId.map(uid => sampleArray.reverse().find(ask => ask.id_ask === uid));
console.log(r);

这里是一个单独的语句:

const sampleArray = [
  {
    id: 1,
    id_ask: 2,
    id_answer: 3
  },
  {
    id: 2,
    id_ask: 2,
    id_answer: 5
  },
    {
    id: 3,
    id_ask: 3,
    id_answer: 3
  },
    {
    id: 4,
    id_ask: 3,
    id_answer: 1
  },
    {
    id: 5,
    id_ask: 4,
    id_answer: 3
  }
];

// put together in a single statement.
const result = [...new Set(sampleArray.map(e => e.id_ask))]
               .map(uid => sampleArray.reverse().find(ask => ask.id_ask === uid));

console.log(result);

注意:对于大型数据集,在使用前一次调用reverse()显然会更有效。

const revArray = myArray.reverse();
const resultArray = [...new Set(revArray.map(e => e.id_ask))]
           .map(uid => revArray.reverse().find(ask => ask.id_ask === uid));