I need to create a new array made up of unique elements from two separate arrays.
I have converted both arrays into a single array and then converted this into an object to check the frequency of the elements. If the value of an object property is 1 (making it a unique property), I want to return it to an array (minus the value). Is there a straightforward way to achieve this?
Edits: Moved result outside for loop. Expected output should be [4]
function diffArray(arr1, arr2) {
var finalArr = [];
var countObj = {};
var newArr = [...arr1, ...arr2];
for (var i = 0; i < newArr.length; i++) {
if (!countObj[newArr[i]]) countObj[newArr[i]] = 0;
++countObj[newArr[i]];
}
for (var key in countObj) {
if (countObj[key] === 1) {
finalArr.push(key);
}
} return finalArr;
}
diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]);
If I understand correctly, you're wanting to find the difference between arr1 and arr2, and returns that difference (if any) as a new array of items (that are distinct in either array).
There are a number of ways this can be achieved. One approach is as follows:
function diffArray(arr1, arr2) {
const result = [];
const combination = [...arr1, ...arr2];
/* Obtain set of unique values from each array */
const set1 = new Set(arr1);
const set2 = new Set(arr2);
for(const item of combination) {
/* Iterate combined array, adding values to result that aren't
present in both arrays (ie exist in one or the other, "difference") */
if(!(set1.has(item) && set2.has(item))) {
result.push(item);
}
}
return result;
}
console.log(diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]), " should be [4]");
console.log(diffArray([1, 2, 3, 5, 8], [1, 2, 3, 5]), " should be [8]");
console.log(diffArray([1, 2, 3, 5, 8], [1, 2, 3, 5, 9]), " should be [8, 9]");
console.log(diffArray([1, 2], [1, 2]), " should be []");
Related
I want to extract a subarray from a multidimensional array and have the original array be mutated so it no longer contains the extracted subarray
If I have a multidimensional array called originalArray
I can extract a subarray from a list of header indices
function newArrCols(arrayofarray, indexlist) {
return arrayofarray.map(function (array) {
return indexlist.map(function (idx) {
return array[idx];
});
});
}
So If:
idxList = [1,2,5,7]
subArray = newArrCols(originalArray, idxList)
Know I have to delete the subArray from the originalArray
//Remove columns from original arr w.r.t headeridx
for (var i = 0; i <= idxList.length - 1; i++) {
originalArray.map(a => a.splice(idxList[i], 1));
}
Is there a way to do this in a single process I would like to skip the deleting part
Thanks
EDIT:
Create a temporary empty array that will hold the items of the originalArray that aren't included in the idxList
let tempArray = [];
Create the subArray and populate the tempArray using Array.reduce():
let subArray = originalArray.reduce((accumulator, current, index) => {
if (idxList.includes(index)) {
//if the current index is included in the idxList array,
//push the current value to the accumulator
accumulator.push(current);
} else {
//push the current value to the `tempArray`.
tempArray.push(current)
}
return accumulator;
}, []);
Replace the originalArray with a deep clone of the tempArray
originalArray = JSON.parse(JSON.stringify(tempArray));
Working snippet below.
let originalArray = [
[0, 0, 0, 0],
[1, 1, 1, 1],
[2, 2, 2, 2],
[3, 3, 3, 3],
[4, 4, 4, 4],
[5, 5, 5, 5],
[6, 6, 6, 6],
[7, 7, 7, 7],
];
let idxList = [1, 2, 5, 7];
let tempArray = [];
//Can also be written in a one line arrow function
let subArray = originalArray.reduce((a, c, i) => (idxList.includes(i) ? a.push(c) : tempArray.push(c), a), []);
originalArray = JSON.parse(JSON.stringify(tempArray));
tempArray = [];
console.log({
subArray: JSON.stringify(subArray)
});
console.log({
originalArrayAfter: JSON.stringify(originalArray)
});
Let's say I have two arrays, where array1 is always changing:
First case:
array1 = [1, 2, 3, 4, 5]
array2 = [1, 2, 3]
How can I compare them and add 4 and 5 into array2?
I am getting the difference between them doing:
let difference = array1.filter(x => !array2.includes(x));
and then doing array2.push(difference), so array2 is now equal to array1, right?
Second case:
array1 = [1, 2, 8, 9]
array2 = [1, 2, 3]
So now I need to remove 3 from array2, and add 8 and 9, how can I do this?
EDIT: I need this because I'm getting array1 from a server(they are chats) and it's dynamically changing every 5 sec, and this is problem. I need to keep the elements I already have so they won't "update" and only change the one getting deleted or added. Hope this makes sense.
First case will not work as aspectedlooking at the code,
to achive what you want you have to write:
difference.forEach((x) => array2.push(x));
instead of:
array2.push(difference)
for the second one if you want to remove a record in array2 because is missing in array1 you need to control each value of array2 in array1 and remove if not exists by ID
var array1 = [1, 2, 8, 9];
var array2 = [1, 2, 3];
//here i build difference2 collecting the value of array2 that miss on array1
let difference2 = array2.filter((x) => !array1.includes(x));
//here with splice and indexOf i remove every value collected before
difference2.forEach((x) => array2.splice(array2.indexOf(x), 1));
//following code is to add the 8 and 9
let difference = array1.filter((x) => !array2.includes(x));
difference.forEach((x) => array2.push(x));
console.log(array2);
//the result [1,2,8,9]
let array1 = [1, 2, 3, 4, 5];
let array2 = [1, 2, 3];
let filteredArray = array2.filter((a) => array1.includes(a));
let secFilteredArray = array1.filter((a) => !filteredArray.includes(a));
console.log(filteredArray.concat(secFilteredArray));
You could take a Set and delete seen items and add the rest to the array.
const
array1 = [1, 2, 8, 9],
array2 = [1, 2, 3],
set1 = new Set(array1);
let i = array2.length;
while (i--) if (!set1.delete(array2[i])) array2.splice(i, 1);
array2.push(...set1);
console.log(array2);
Just use another filter and combine the two arrays.
const array1 = [1, 2, 8, 9];
let array2 = [1, 2, 3];
const inArrOne = array1.filter(x => !array2.includes(x));
const inBothArr = array2.filter(x => array1.includes(x));
array2 = [...inBothArr, ...inArrOne];
console.log(array2);
I would avoid much built-in or third party compare functions since I am not sure what I am dealing with. This could be refactored and optimized more if the array1 is guaranteed to have an ordered list.
let localArray = [1, 2, 3, 4, 5],
lastServerArray = [];
/**
* Compares "fromArr" to "targetArr"
* #param fromArr Array of elements
* #param targetArr Array of elements
* #returns List of elements from "fromArr" that do not happen in "targetArr"
*/
const compArr = (fromArr, targetArr) => {
const result = [];
for (let i = 0, len = fromArr.length; i < len; i++) {
const elem = fromArr[i],
targetIdx = targetArr.indexOf(elem);
if (!~targetIdx && !~result.indexOf(elem)) {
// Element do not exist in "targetArr" and in current "result"
result.push(elem);
}
}
return result;
}
const updateLocalArray = (serverArray = []) => {
if (JSON.stringify(lastServerArray) === JSON.stringify(serverArray)) {
console.log('Nothing changed from server, skip updating local array');
return localArray;
}
lastServerArray = serverArray;
const notExistentLocalElems = compArr(serverArray, localArray), // Elements that do not exists in local array
notExistentServerElems = compArr(localArray, serverArray); // Elements that do not exists in server array
// Do something to those "notExistentLocalElems" or "notExistentServerElems"
// ---
// Sync server array to local array
// Remove elements that is not on server.
localArray = localArray.filter(elem => !~notExistentServerElems.indexOf(elem));
console.log('These elements removed from localArray', notExistentServerElems);
// Append elements that is on server.
localArray.push(...notExistentLocalElems);
console.log( 'These elements added into localArray', notExistentLocalElems);
return localArray;
}
updateLocalArray([1, 2, 3]);
console.log(`1. server sends [1, 2, 3] -- local becomes`, localArray);
updateLocalArray([3, 4, 5, 6]);
console.log(`2. server sends [3, 4, 5, 6] -- local becomes`, localArray);
updateLocalArray([5, 5, 4, 2, 7]);
console.log(`3. server sends [5, 5, 4, 2, 7] -- local becomes`, localArray);
updateLocalArray([0, 0, 1, 2]);
console.log(`4. server sends [0, 0, 1, 2] -- local becomes`, localArray);
You could do like this if you want to mutate array2:
let array1 = [1, 2, 8, 9];
let array2 = [1, 2, 3];
let valuesToAdd = array1.filter(x => !array2.includes(x));
let indexesToDelete = Object.entries(array2).filter(([, x]) => !array1.includes(x)).map(([i]) => i);
// Reverse iteration to preserve indexes while removing items
indexesToDelete.reverse().forEach(i => array2.splice(indexesToDelete[i], 1));
array2.push(...valuesToAdd);
console.log(array2);
How to sort randomly placed values in one array so that it matches the order provided by another array, but instead of appending the duplicates one after the other, the function should append the group of values, provided by the order variable, one after the other.
Input:
const array = [1, 5, 4, 3, 5, 3, 1, 5, 4];
const order = [5, 1, 3, 4];
Correct Output:
const correctlyOrderedArray = [5, 1, 3, 4, 5, 1, 3, 4, 5];
Wrong Output:
const wronglyOrderedArray = [5, 5, 5, 1, 1, 3, 3, 4, 4];
Two functions. The first one does the actual sorting and uses the second one inside itself.
Primary function:
function sortByOrder (array, order) {
const arrayOfArrays = order.map(v => {
return [...Array(howMany(v, array))].map(undef => v);
});
const tempArray = [];
arrayOfArrays.forEach((subArr, i) => {
let index = order.indexOf(order[i]);
subArr.forEach(duplicate => {
tempArray[index] = duplicate;
index += order.length;
});
});
return tempArray.filter(v => v);
}
Subordinate function:
function howMany(value, array) {
const regExp = new RegExp(value, 'g');
return (array.join(' ').match(regExp) || []).length;
}
If we suppose that the array order contains all the non duplicated elements of the array array, one way to achieve the sorting could be to copy the element of order using a modulo so that, we can restart the copy from the beginning.
const array = [1, 5, 4, 3, 5, 3, 1, 5, 4];
const order = [5, 1, 3, 4];
var newValue = []
for(var i = 0; i < array.length; i++){
newValue.push(order[i % order.length])
}
console.log(newValue)
We could iterate over the order and shift out elements out of our array until its empty:
const array = [1, 5, 4, 3, 5, 3, 1, 5, 4];
const order = [5, 1, 3, 4];
let i = 0, exit = false;
const result = [];
while(array.length){
const found = array.findIndex(el => el === order[i % order.length]);
if(found+1){
result.push( array.splice(found, 1)[0] );
exit = false;
}
if(i && i % order.length){
if(exit){
result.push(...array); //concat the rest
break;
}
exit = true;
}
i++;
}
The exit boolean will terminate the program if one order iteration did not found anything, e.g.:
const order = [1,2,3], array = [4,5,6,1,2,3,1,2,3];
Let it run!
I have the following function which is supposed to remove the smallest value from an array, but if this is a duplicate it will just remove the first one and leave the others.
var array1 = [1, 2, 3, 4, 5];
var array2 = [5, 3, 2, 1, 4];
var array3 = [2, 2, 1, 2, 1];
function removeSmallest(numbers) {
return numbers.filter(function(elem, pos, self) {
if(elem == Math.min.apply(null, numbers) && pos == self.indexOf(elem)) {
// Remove element from Array
console.log(elem, pos);
numbers.splice(pos, 1);
};
return numbers;
});
};
Via console.log(elem, pos) I understand that I have correctly identified the smallest and first element in the array, but when I try to remove it through splice(), I end up getting the following result for the arrays:
array1 = [1, 3, 4, 5]; // But I expected [2, 3, 4, 5]
array2 = [5, 3, 2, 1]; // But I expected [5, 3, 2, 4]
array3 = [2, 2, 1, 1]; // But I expected [2, 2, 2, 1]
Do you know what is the issue with my code? Thanks in advance for your replies!
function removeSmallest(numbers) {
const smallest = Math.min.apply(null, numbers);
const pos = numbers.indexOf(smallest);
return numbers.slice(0, pos).concat(numbers.slice(pos + 1));
};
You shouldn't use filter() the way you do. It's also a good practice that a function should return a new array rather than modifying the existing one and you definitely shouldn't modify an array while iterating over it.
function removeSmallest(arr){
var temp=arr.slice(),smallElement=null;
temp.sort(sortReverse);
smallElement=temp[temp.length-1];
var position=arr.indexOf(smallElement);
arr.splice(pos,1);
console.log(arr);
}
function sortReverse (a,b){
if(a<b){return 1}
else if(a>b){return -1;}
else{return 0;}
}
var array1 = [1, 2, 3, 4, 5];
removeSmallest(array1);
When I want to remove one element, it is easy. This is my function:
function removeValues(array, value) {
for(var i=0; i<array.length; i++) {
if(array[i] == value) {
array.splice(i, 1);
break;
}
}
return array;
}
But how do I remove multiple elements?
Here a simple version using ES7:
// removing values
let items = [1, 2, 3, 4];
let valuesToRemove = [1, 3, 4]
items = items.filter((i) => !valuesToRemove.includes(i))
For a simple version for ES6
// removing values
let items =[1, 2, 3, 4];
let valuesToRemove = [1, 3, 4]
items = items.filter((i) => (valuesToRemove.indexOf(i) === -1))
const items = [0, 1, 2, 3, 4];
[1, 4, 3].reverse().forEach((index) => {
items.splice(index, 1)
})
// [0, 2, 4]
I believe you will find the kind of functionality you are looking for in Javascript's built in array functions... particularily Array.map(); and Array.filter();
//Array Filter
function isBigEnough(value) {
return value >= 10;
}
var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
// filtered is [12, 130, 44]
//Array Map (Can also be used to filter)
var numbers = [1, 4, 9];
var doubles = numbers.map(function(num) {
return num * 2;
});
// doubles is now [2, 8, 18]. numbers is still [1, 4, 9]
/////UPDATE REFLECTING REMOVAL OF VALUES USING ARRAY MAP
var a = [1,2,3,4,5,6];
a.map(function(v,i){
if(v%2==0){
a.pop(i);
}
});
console.log(a);
// as shown above all array functions can be used within the call back to filter the original array. Alternativelty another array could be populated within the function and then aassigned to the variable a effectivley reducing the array.