8

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!

2
  • 3
    Everything is possible in JS without jQuery, since jQuery is written in JS. Commented Feb 17, 2017 at 11:57
  • @Emily,it worked my solution for you ? Commented Feb 17, 2017 at 15:45

2 Answers 2

5

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);

Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.