Remove an array of elements from another array - arrays

I have an array array1 = [1,2,3,4,5,6] and another array array2 = [4,5].
The objective is to remove array2's elements from array1 with the least time complexity.
Final array is [1,2,3,6]
I know we can do something like this for every element
function remove(array, element) {
return array.filter(e => e !== element);
}
let array1 = [1,2,3,4,5,6];
array2 = [4,5];
array2.forEach(el => {
array1 = remove(array1, el);
});
How do i make it better?

I have two solutions for you :
var arr1 = [ 1, 2,3 ];
var arr2 = [1,2,4 ];
var result = arr1.filter(o1 => arr2.filter(o2 => o2 === o1).length === 0);
console.log(result);
Or you can use difference of Loadash

Simpler and cleaner
const arr1 = [1,2,3,4]
const arr2 = [3,4]
const newArray = arr1.filter( x => !arr2.includes(x))
console.log(newArray)

Related

Is there a way to update a readonly array of objects

I do have two arrays
arr1 = [1,2,3,4] //readonly array
arr2 = [1,2,3,4,5,6,7]
arr1 is the main array and I want to update it with contents from arr2 so that when i log arr1 it will display
[1,2,3,4,5,6,7]
is there a way I can do this
let arr1 = [1,2,3,4];
let arr2 = [1,2,3,4,5,6,7];
arr1 = [...new Set([...arr1 ,...arr2])];
console.log(arr1); // [1,2,3,4,5,6,7]
var mergedArray = new Array(...arr1, arr2) // [1,2,3,4,1,2,3,4,5,6,7]
var finalArray = []
mergedArray.forEach(item => {
if (!finalArray.includes(element)) {
finalArray.push(element);
}
})
console.log(finalArray) // [1,2,3,4,5,6,7]
mergedArray will be a new array that we create by merging both arr1 and arr2. Then we check for unique elements in mergedArray by using the forEach method and add non-repeating elements to finalArray.

How to check all elements in an array same as some element in the other array

I have a question about How to check all elements in an array same as some elements in other array.
array1= [[1,2], [2,3], [3,3]]
array2 = [[1,2],[2,3]]
so in this case it will return true, because all the elements in array2 are same as array1.
Doses anybody some solution
What you want to do is use Array.prototype.some() to calculate intersection between your two arrays. A nested .some() is needed, because we need to stringify the arrays and compare them as JSON string, since [1,2] !== [1,2], for example.
See proof-of-concept code below:
const array1 = [[1,2], [2,3], [3,3]];
const array2 = [[1,2],[2,3]];
const array3 = [[3,4],[4,5]];
const array4 = [[3,3]];
function isIntersecting(arr1, arr2) {
return arr1.some(x => {
return arr2.some(y => {
return JSON.stringify(x) === JSON.stringify(y);
});
});
}
console.log(isIntersecting(array1, array2)); // Should return true
console.log(isIntersecting(array1, array3)); // Should return false
console.log(isIntersecting(array2, array3)); // Should return false
console.log(isIntersecting(array1, array4)); // Should return true

Convert multidimension array to different arrays in javascript

I have an array in javascript shown below
var multiArray = [['Jan',12],['Feb',13],['Mar',14]];
Now i want the elements of the above array elements into two seperate arrays as
var array1 = ['Jan','Feb','Mar'];
var array2 = [12,13,14];
Which methodology should i use to convert them as separate arrays.?
You could use a Map to convert them
const multiArray = [['Jan',12],['Feb',13],['Mar',14]];
const m = new Map(multiArray);
const arr1 = Array.from(m.keys());
const arr2 = Array.from(m.values());
console.log(arr1, arr2);
In your case this is the easiest approach:
var multiArray = [['Jan',12],['Feb',13],['Mar',14]];
var arr1 = multiArray.map(x => x[0])
var arr2 = multiArray.map(x => x[1])

How to search a subarray of numbers inside an array of numbers

my issue is this in TypeScript (now latest is v3.1)
I have a array of numbers
let mainArray : Array<number> = [1,2,3,4];
I have to find subarray of [2,3], how can i do?
My actual workaround is converting both arrays in string (toString()) and using .includes (ES6) function, and it works but i think is not the best solution.
Thank you!
You can use filter for this
let mainArray : Array<number> = [1,2,3,4];
var findArry = [2, 3];
var subArray = mainArray.filter(function(val) {
return findArry.indexOf(val) != -1 ? true : false;
});
console.log(subArray);
Well its more algorithm problem then typescript problem. But this solution should work for checking if there is subarray which matched with searched array:
const toTuples = (n) => (item, index, originalArr) => {
const arr = [];
for(let i = 0; i < n; i++) {
arr.push(originalArr[index + i]);
}
return arr;
}
const arr = [1,2,3,4,2,3];
const search = [2, 3];
const mapped = arr.map(toTuples(search.length));
console.log(mapped.some((currArray) => currArray.every((item) => search.includes(item))));

JS - filter array of objects by array of property values and return array of filtered objects

I am trying (in js or jquery) to filter array of objects and return array of objects that have particular property name.
I tried filter and find functions like this:
var objs = [{ a:1, }, {a:2}, {a:3}, {a:4}]
var vals = [1, 2]
function callback(obj) {
var arr = arr || []
console.log(arr)
$.each(vals, function(key, val) {
if ( val == obj.a ) {
arr.push(obj)
}
})
}
var result = objs.find(callback);
console.log(">>>", result)
Expected result is:
result = [{a:1}, {a:2}]
However it doesnt work because each iteration of find starts over and defines arr all over again.
I could ofcourse make is with two nested $.each() - one to iterate through array of objects and second to iterate through array of property values but i consider is as last option - looking for something more elegant, shorter. Do you guys have any ideas?
You could do it with a filter and indexOf.
var objs = [{ a:1, }, {a:2}, {a:3}, {a:4}]
var vals = [1, 2]
function filterByValue(source, allowedValues) {
// Return the result of the filter.
return source.filter(item => {
// Returns true when `a` is present in vals (index > -1); otherwise it returns false.
return allowedValues.indexOf(item.a) > -1;
});
}
const
filteredArray = filterByValue(objs, vals);
console.log(filteredArray)
Thijs's answer works, but will get unperformant as the vals array gets large. To get O(n) complexity, you could build a set out of the allowedValues array:
var objs = [{ a:1, }, {a:2}, {a:3}, {a:4}]
var vals = [1, 2]
function filterByValue(source, allowedValues) {
allowedValues = new Set(allowedValues)
// Return the result of the filter.
return source.filter(item => {
// Returns true when `a` is present in vals, otherwise it returns false.
return allowedValues.has(item.a);
});
}
const filteredArray = filterByValue(objs, vals);
console.log(filteredArray)

Resources