Remove Same values array Jquery - javascript

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

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;

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 object from array if it is contained in another array

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

Having trouble getting rid of duplicates in JavaScript.

var numberArray = [1,2,3,4, 5,6,7,8,9, 9, 4];
var newArray = [];
function primeChecker(arrayCheck){
for (var i = 0; i < arrayCheck.length; i++){
if (Math.sqrt(arrayCheck[i]) % 1 === 0) {
newArray.push(arrayCheck[i]);
}
}
for (var x = 0; x < newArray.length; x++){
newArray.sort();
if (newArray[x] === newArray[x -1]){
newArray.splice(newArray[x-1]);
}
}
}
primeChecker(numberArray);
console.log(newArray);
The returned array is [ 1, 4, 4, 9 ]. The function successfully gets rid of the repeating 9s but I am still left with two 4s. Any thoughts as to why this might be? I am a JavaScript beginner and not totally familiar with the language.
Loop backwards. When you remove the item from the array the array gets shorter.
https://jsfiddle.net/2w0k5tz8/
function remove_duplicates(array_){
var ret_array = new Array();
for (var a = array_.length - 1; a >= 0; a--) {
for (var b = array_.length - 1; b >= 0; b--) {
if(array_[a] == array_[b] && a != b){
delete array_[b];
}
};
if(array_[a] != undefined)
ret_array.push(array_[a]);
};
return ret_array;
}
console.log(remove_duplicates(Array(1,1,1,2,2,2,3,3,3)));
Loop through, remove duplicates, and create a clone array place holder because the array index will not be updated.
Loop backward for better performance ( your loop wont need to keep checking the length of your array)
You do not need insert the number that already is in newArray, you can know what element is in the array with the method indexOf.
Try it in the if, and you can delete the second cicle for.
Something like this:
if (Math.sqrt(arrayCheck[i]) % 1 === 0 && newArray.indexOf(arrayCheck[i])==-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