Remove object from array if it is contained in another array - javascript

I am trying to remove an object from an array, if that object's property (unique) is included in the other array. I know I can do a nested for-loop like this:
for(i = 0; i < array.length; i++) {
for(j = 0; j < array2.length; j++) {
if(array[i].Email === array2[j].Email) {
//remove array[i] object from the array
}
}
}
Or whatever. Something like that. Is there an ES6 filter for that? I can easily do a filter up against a regular array with strings, but doing it with an array of objects is a bit more tricky.

If you are fine using ES6, you can even look into array.find, array.filter or array.some
Array.findIndex
var result = array.filter(x=>{
return array2.findindex(t=> t.Email === x.Email) === -1
})
Array.some
var result = array.filter(x=>{
return !array2.some(t=> t.Email === x.Email)
})

Not very optimal, but try this
array = array.filter( function( item ){
return array2.filter( function( item2 ){
return item.Email == item2.Email;
}).length == 0;
});
Try with find as well, it won't iterate all the elements and will break after first match itself
array = array.filter( function( item ){
return array2.find( function( item2 ){
return item.Email == item2.Email;
}) == undefined;
});

You could use a Set with ES6
var array = [/* your data */],
array2 = [/* your data */],
set = new Set(...array2.map(a => a.Email));
array = array.filter(a => !set.has(a.Email));

Try this one.... :)
if(array[i].Email === array2[j].Email){
// splice(Index you want to remove,to witch element)
array1.splice(i,1);
}
splice() can remove element of your array. You need to pass witch element. witch element is the start of delete. How many elements should delete. That's 1.. :)

How about writing a function, passing the parameters and simply collecting the output?
function arrNotInArrKey(arr1, arr2, key) {
for (var i = 0; i < arr1.length; i++) {
for (var j = 0; j < arr2.length; j++) {
if (arr1[i][key] === arr2[j][key]) {
arr1.splice(i, 1);
i--;
}
}
}
return arr1;
}
console.log(
arrNotInArrKey([{
name: 1
}, {
name: 3
}, {
name: 2
}], [{
name: 2
}], "name")
);

You can use shift function. here it's example.
http://www.w3schools.com/js/tryit.asp?filename=tryjs_array_shift
for(i = 0; i < array.length; i++) {
for(j = 0; j < array2.length; j++) {
if(array[i].Email === array2[j].Email) {
array.shift(array[i].Email);
}
}
}

Related

How to create javascript array when each element is a pair of objects

hello I would like to build an array that every element will be a pair of objects , Something like this
var Shelves = new arr[][]
var books = new Books[] ;
Shelves[book[i],book[j=i+1]],[book[i+1],book[j=i+1]] and so on......;
I mean that I understand how to go with a for loop and to get the elements 'but how to push them in pairs array? arr.push doesn't work :(
build1ArrPairs(1Arr) {
if (1Arr != undefined || 1Arr!=null) {
for (var i = 0; i < 1Arr.length; i = i + 1) {
for (var j = i + 1; j <= 1Arr.length; j++) {
this.1ArrPair.push(1Arr[i] 1Arr[j]);
break;
}
}
}
}
Thanks :)
Alternatively, you can use array#reduce to group your array.
var names = ['a', 'b','c','d','e'];
var result = names.reduce((r,w,i) => {
let index = Math.floor(i/2);
if(!Array.isArray(r[index]))
r[index] = [];
r[index].push(w);
return r;
},[]);
console.log(result);
First of all, variables names can't start with a number.
Second, initialize an array, then add your elements - two at a time - and return the array:
var ans = [];
if (Arr != undefined || Arr != null) {
for (var i=0; i<(Arr.length-1); i+=2) { // Note the loop stops 2 elements before the last one
ans.push([Arr[i], Arr[i+1]]);
// ^ Note the comma - it's missing in your code
}
}
return ans;

Remove sub-array contains common elements

As the title, if the input is [[1,2], [3,4], [1,3], [5,6], [6,5]], output should be [[1,2,3,4], [5,6]].
It's wrong on the recursive part. In my code, after running it, I will get [[1,2,3],[1,3,4],[5,6]], which means I need once more merge, but I'm confused how to continue the code until no sub-array contains common element.
Here is my code
function need_merge_or_not(arr)
{
for (var i = 0; i <= arr.length-1; i++) {
for (var j = i+1; j <= arr.length-1; j++) {
var arr_new = arr[i].concat(arr[j]);
//remove deplicates
var arr_merge = arr_new.filter(function (item, pos) {return arr_new.indexOf(item) == pos});
if (arr_merge.length < arr_new.length) {
return true;
}
}
}
return false;
}
function merge(arr)
{
if (arr.length >= 2) {
for (var i = 0; i <= arr.length-1; i++) {
for (var j = i+1; j <= arr.length-1; j++) {
var arr_new = arr[i].concat(arr[j]);
var arr_merge = arr_new.filter(function (item, pos) {return arr_new.indexOf(item) == pos});
if (arr_merge.length < arr_new.length) {
arr.splice(arr.indexOf(arr[i]), 1);
arr.splice(arr.indexOf(arr[j]),1);
arr.push(arr_merge);
}
}
if (need_merge_or_not(arr)) {
return merge(arr);
}
}
}
return arr;
}
I figured it out. Here is the code:
function merge(arr){
var input = [];
for(var i = 0; i < arr.length; i++){
input.push(arr[i]);
}
if (arr.length >= 2) {
for (var i = 0; i < arr.length; i++) {
for (var j = i+1; j < arr.length; j++) {
var arr_new = arr[i].concat(arr[j]);
//remove duplicates
var arr_merge = arr_new.filter(function (item, pos) {return arr_new.indexOf(item) == pos});
if (arr_merge.length < arr_new.length) {
arr.splice(arr.indexOf(arr[i]), 1, arr_merge);
arr.splice(arr.indexOf(arr[j]),1);
j--;
}
}
}
if (!arraysEqual(input, arr)) {merge(arr)};
}
return arr;
//Input:[[1,2], [3,4], [1,3], [5,6], [6,5]]
//Output:[[1,2,3,4], [5,6]]
}
function arraysEqual(a, b) {
if (a === b) return true;
if (a == null || b == null) return false;
if (a.length != b.length) return false;
for (var i = 0; i < a.length; ++i) {
if (a[i] !== b[i]) return false;
}
return true;
}
You could use two hash tables, one for the items and their groups and on for the result sets.
Basically the algorithm generates for the same group an object with a property and an array, because it allowes to keep the object reference while assigning a new array.
The main part is iterating the outer array and then the inner arrays and check inside, if it is the first item, then check the hash table for existence and if not exists, generate a new object with a values property and an empty array as value. Also assign the actual object to sets with item as key.
In a next step, the hash table is checked again and if not exist, then assign the object of the first element.
To maintain only unique values, a check is made and if the item does not exist, the item is pushed to the hash table's values array.
Then a part to join arrays follows by checking if the object of the first item is not equal to object of the actual item. If so, it delete from sets the key from the actual items's values first item and concat the array of the actual items to the first item's object's values. Then the values object is assigned to the actual item's object.
Later the sets are maped to the result set with iterating the sets object and the values property is taken as value.
var array = [[1, 2], [3, 4], [1, 3], [5, 6], [6, 5]],
groups = {},
sets = {},
result;
array.forEach(function (a) {
a.forEach(function (b, i, bb) {
if (i === 0 && !groups[b]) {
groups[b] = { values: [] };
sets[b] = groups[b];
}
if (!groups[b]) {
groups[b] = groups[bb[0]];
}
if (groups[b].values.indexOf(b) === -1) {
groups[b].values.push(b);
}
if (groups[bb[0]] !== groups[b]) {
delete sets[groups[b].values[0]];
groups[bb[0]].values = groups[bb[0]].values.concat(groups[b].values);
groups[b].values = groups[bb[0]].values;
}
});
});
result = Object.keys(sets).map(function (k) {
return sets[k].values;
});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

How to use a key array to remove specific items from a main array?

First of all thank you to whoever reads this whole question. I am having trouble writing a function that can take a key array and use the indices to remove like items from a main array.
My main Array
var mainArray = [
{fruit:"apple",color:"red"},
{fruit:"orange",color:"orange"},
{fruit:"banana",color:"yellow"},
{fruit:"apple",color:"red"},
{fruit:"banana",color:"yellow"},
{fruit:"mango",color:"greenishyellowishred"}
]
Array of items will be added to this mainArray and I need to remove multiple items at a time.
My key Array
var keyArray = [{fruit:"apple",color:"red"}, {fruit:"banana",color:"yellow"}]
I am attempting to remove the "apple" and the "banana" by using a for loop to decrement through the array to maintain the integrity of the mainArray.
for(var i = mainArray.length - 1; i > -1; i--) {
for(var j = keyArray.length - 1; j > -1; j--) {
if(mainArray[i].fruit === keyArray[j].fruit) {
mainArray.splice(i, 1)
keyArray.splice(j, 1)
}
}
}
My issue comes when I am trying to read mainArray[i].fruit if i = 0
Thanks in advance for any help possible.
Try the following way:
var mainArray = [
{fruit:"apple",color:"red"},
{fruit:"orange",color:"orange"},
{fruit:"banana",color:"yellow"},
{fruit:"apple",color:"red"},
{fruit:"banana",color:"yellow"},
{fruit:"mango",color:"greenishyellowishred"}
];
var keyArray = [{fruit:"apple",color:"red"}, {fruit:"banana",color:"yellow"}];
var tempArray = [];
for(let j = 0; j < keyArray.length; j++) {
for(let i = 0; i < mainArray.length; i++) {
if(mainArray[i].fruit === keyArray[j].fruit) {
tempArray.push(mainArray[i]);
}
}
}
mainArray = mainArray.filter( function( el ) {
return !tempArray.includes( el );
});
console.log(mainArray);

Remove Same values array Jquery

How do I remove the repeated array which has the same values as the first array. Below is the array I have. Can anyone help me out on this.
I need to remove the repeated array which is second one and show only the 1st array.
JS:
arr = [ [10,20] , [10,20] ]
jQuery's unique only works on DOM elements, I think what you are looking for is the uniq from the underscore library, which can be found at http://underscorejs.org/#uniq
You can try
function arraysEqual(a1,a2) {
return JSON.stringify(a1)==JSON.stringify(a2);
}
Try this:-
var arr = [ [10,20] , [30,20],[10,40],[10,20],[30,20] ],newArr=[];
$.each(arr, function(index,item){
if(searchForItem(newArr,item)<0){
newArr.push(item);
}
})
console.log(newArr);
function searchForItem(array, item){
var i, j, current;
for(i = 0; i < array.length; ++i){
if(item.length === array[i].length){
current = array[i];
for(j = 0; j < item.length && item[j] === current[j]; ++j);
if(j === item.length)
return i;
}
}
return -1;
}

Javascript: Filtering twodimensional array

There's plenty examples available on how to sort an javascript array based on it's numeric values. What would however be appropriate way to fetch all elements from myArray with the property prop1 with it's according value value1?
Here's my array:
var myArray = [
{
"id":"2",
"name":"My name",
"properties":{"prop1":"value1"}
}];
Thanks
You can just access it by dot or bracket notation and push the matching members to your new/filtered array, for example:
var newArray = [];
for(var i=0, l = myArray.length; i<l; i++) {
if(myArray[i].properties.prop1 == "value1") newArray.push(myArray[i]);
}
Your question is a bit ambiguous though, if you're trying to get the {"prop1":"value1"} object, not the parent, then just change newArray.push(myArray[i]) to newArray.push(myArray[i].properties).
Provide a compare function to sort by arbitrary properties:
function compareMyObjects(a, b) {
var valA = a.properties.prop1.value1;
var valB = b.properties.prop1.value1;
if(valA > valB) return 1;
if(valA < valB) return -1;
return 0;
}
myArray.sort(compareMyObjects);
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort
Go through each element in your array. For each element, check each property to see if it matches the one you're looking for.
function filterArray(array, property, value) {
var newArray = [];
for (var i = 0; i < array.length; i++) {
for (var j in array[i].properties) {
if (j === property && array[i].properties.hasOwnProperty(j)) {
if (array[i].properties[j] == value) {
newArray.push(array[i]);
}
}
}
}
}
var newarray=myarray.filter(function(itm){
return itm.properties.prop1==='value1';
});
Filter, like the array methods indexOf and map, may be worth providing for browsers that don't have it- this version is from Mozilla Developer Site-
if(!Array.prototype.filter){
Array.prototype.filter= function(fun, scope){
var L= this.length, A= [], i= 0, val;
if(typeof fun== 'function'){
while(i< L){
if(i in this){
val= this[i];
if(fun.call(scope, val, i, this)){
A[A.length]= val;
}
}
++i;
}
}
return A;
}
}

Categories

Resources