简体   繁体   中英

Filter array if element is present in another array based on value

I have an object array like this:

var objectArray = [{id_5:"100"},
                   {id_1:"300"},
                   {id_2:"500"},
                   {id_4:"700"},
                   {id_3:"200"}];

And a normal array like this:

var normalArray = ["id_2","id_5","id_4"];

I want to subtract every element from the objectArray if there's a matching ID in the normalArray. I then want to order the newly created array by the object's value (lowest value being first).

So for the above example the result would be:

var newObjectArray = [{id_3:"200"},
                      {id_1:"300"}];

Is it possible to do this without jQuery?

I've seen similar questions like this one: Removing object from one array if present in another array based on value but I haven't been able to find an answer that works. Is it possible to do a compare and remove like this while still keeping the key:value pairs intact? Thanks in advance for any help with this!

You should use filter method, which accepts as parameter a callback function.

Also, you have to use Object.keys() method in order to get the key of each object in objectArray .

To check if an element from objectArray doesn't appear in objectArray , you should use indexOf() method.

To achieve the sorted array, you have to use sort() method.

 var objectArray = [{id_5:"100"}, {id_1:"300"}, {id_2:"500"}, {id_4:"700"}, {id_3:"200"}]; var normalArray = ["id_2","id_5","id_4"]; var newArray=objectArray.filter(function(item){ return normalArray.indexOf(Object.keys(item)[0]) == -1; }).sort(function(a,b){ return a[Object.keys(a)[0]] - b[Object.keys(b)[0]]; }); console.log(newArray); 

You can first use filter() to remove object with key from other array and then sort to sort result array by objects value.

 var objectArray = [{id_5:"100"},{id_1:"300"},{id_2:"500"},{id_4:"700"},{id_3:"200"}]; var normalArray = ["id_2","id_5","id_4"]; var newArray = objectArray .filter(e => !normalArray.includes(Object.keys(e)[0])) .sort((a, b) => a[Object.keys(a)[0]] - b[Object.keys(b)[0]]) console.log(newArray) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM