I have an object

var data = [{"кришна":"верно1","topic_id":"39875"}, {"кришна":"верно2","topic_id":"39875"}, {"харе":"madare","topic_id":"39872"}, {"харе":"верно3","topic_id":"39875"}, {"харе":"fufuf","topic_id":"39873"}, {"8-()":"gagaga","topic_id":"39871"} ]; 

I need to remove all duplicate items from it by topic_id. How can I solve this issue?

  • one
    Loop over all elements, in a loop the operation of adding to a new array, if the object with topic_id does not exist in the new array. - user218976

3 answers 3

 var data = [ {"кришна":"верно1","topic_id":"39875"}, {"кришна":"верно2","topic_id":"39875"}, {"харе":"madare","topic_id":"39872"}, {"харе":"верно3","topic_id":"39875"}, {"харе":"fufuf","topic_id":"39873"}, {"8-()":"gagaga","topic_id":"39871"} ] var newData = [] data.forEach(function(item, i, data){ if ( !doesIncludeByTopicId(newData, item.topic_id) ){ newData.push(item) } }) console.log('data = ', data); console.log('newData = ', newData); /** Check if an array includes an object with property "topic_id" equal to the option "topic_id" * * @param {array} array * @param {string} topic_id * * @return {boolean} */ function doesIncludeByTopicId(array, topic_id) { for (var i=0; i<array.length; i++){ if (array[i].topic_id === topic_id) return true } return false } 

    I will offer a more modern and concise solution.

     const data = [ {"кришна":"верно1","topic_id":"39875"}, {"кришна":"верно2","topic_id":"39875"}, {"харе":"madare","topic_id":"39872"}, {"харе":"верно3","topic_id":"39875"}, {"харе":"fufuf","topic_id":"39873"}, {"8-()":"gagaga","topic_id":"39871"} ]; const uniqueTopicIdsMap = data.reduce((prev, item) => { prev[item.topic_id] = item; return prev; },{}); const result = Object.keys(uniqueTopicIdsMap).map(topicId => uniqueTopicIdsMap[topicId]); console.log(result); 

      Well, if we are talking about a modern and concise, then here's another option.

       var data = [ {"кришна":"верно1","topic_id":"39875"}, {"кришна":"верно2","topic_id":"39875"}, {"харе":"madare","topic_id":"39872"}, {"харе":"верно3","topic_id":"39875"}, {"харе":"fufuf","topic_id":"39873"}, {"8-()":"gagaga","topic_id":"39871"} ] var newData = data.filter(function(elem){ if (this[elem.topic_id]) return false; return this[elem.topic_id] = true },{}) console.log(data); console.log(newData);