Devrim Devrim - 7 days ago 4x
Javascript Question

Javascript - Remove value from array if it doesn't exist in another

I have two arrays:

//list elements from html
var list = document.querySelectorAll('#pres-list-ul li');
//list of retrieved objects from api
var objects = self.retrievedItems;

The contents of list is saved on a html file for efficiency (no need to re-render same data unless you refresh)

I want to remove a list item from the html if it doesn't exist anymore in the retrieved objects.

I know it is somewhere along the lines of the code below but I couldn't work it out.

//I need to compare the id? For that another loop - which will run hundreds and thousands of time?
for(var j = 0; j < objects.length; j++) {
if(objects.indexOf(list[i]) === -1) {
} else {


list: 57 //local
objects: 56 //online

Find that extra value in list and remove it.


<li id="item-5756" data-category="" data-group="" data-created="" data-author=""></li>


0: {
id: //
title: //
description //
// ...

1: {


First you have to somehow align the data. I suggest you get rid of the id="item-5756" for the items. Use data-id="5756" instead. After you have list of ids for local and remote, you can do what you suggested with the indexOf and just hide the local elements that are not in remote.

Check it out here:

var remote_data = {
    5756: {
        id: 5756,
        title: '',
        description: '',
    5757: {
        id: 5757,
        title: '',
        description: '',
    5758: {
        id: 5758,
        title: '',
        description: '',

$(document).on('click', '.filter', filter_local)

function filter_local () {
    var local_ids = $('#pres-list-ul li').toArray().map(function (element) { return $(element).data('id') })
    var remote_ids = []
    for (remote_index in remote_data) {
    console.log(local_ids, remote_ids)

    for (local_id in local_ids) {
        if (remote_ids.indexOf(local_ids[local_id]) == -1) {
            $('#pres-list-ul li[data-id="' + local_ids[local_id] + '"]').hide()

Note that there are several ways for improvement:

Better filtering algorithm: What I suggested has pretty bad efficiency. The ids can be sorted and filtered in one go. The lookup with [data="5678"] is rather slow as well.

Using data binding: Consider using angular or some other mvc framework to make your project maintainable. This way you can just keep track of one list of elements and let angular figure out the re-rendering.