I have a problem needing two arrays containing some similar values and different values. I need to concat the arrays into a new array and remove the similar values only showing the individual values. something like arr1 = [1, 44, 2, 3, 5], arr2 = [33, 1, 2, 3, 4, 5], arr3 = [], return arr3 [44, 33, 4]. I have tried a few different ways with no success, one using a nested for loop and the other using .filter(). Any thoughts on how I can solve this? Here is my code:
const arrayDiffs = (arr1, arr2) => {
let arr3 = [];
for (let i = 0; i < arr1.length; i++) {
if (arr3.indexOf(arr1[i]) === -1) {
arr3.push(arr1[1]);
}
for (let n = 0; n < arr2.length; n++) {
if (arr3.indexOf(arr2[n]) === -1) {
arr3.push(arr2[n]);
}
}
return arr3;
};
}
console.log(arrayDiffs([1, 44, 2, 3, 5], [33, 1, 2, 3, 4, 5]));
I have also tried this way:
let arr3 = [];
const arrayDiffs = (arr1, arr2) => {
arr3 = arr1.concat(arr2);
arr3 = arr3.filter(function(item, index) {
if(arr3.indexOf(item) == index){
return true;
}
return false;
});
}
console.log(arrayDiffs([1, 44, 2, 3, 5], [33, 1, 2, 3, 4, 5]));
const myFunc = (a,b) => {
const a_but_not_b = a.filter(x=>!b.includes(x));
const b_but_not_a = b.filter(x=>!a.includes(x));
return [...a_but_not_b,...b_but_not_a];
}
console.log(myFunc([1,2,3],[2,3,4]));
But, let me explain more:
Use filter and includes to get difference.
Last I concat the arrays using spread operator [...a,...b].
Using your first method only we can achieve this. You have to do the following modifications.
for (let i = 0; i < arr1.length; i++) {
if (arr2.indexOf(arr1[i]) === -1) { // first compare the value with arr2 and arr1 and push the non-available values into arr3
arr3.push(arr1[i]);
}
}
for (let n = 0; n < arr2.length; n++) {
if (arr1.indexOf(arr2[n]) === -1) { //compare the value with arr1 and arr2 and push the non-available values into arr3
arr3.push(arr2[n]);
}
}
const arrayDiffs = (arr1, arr2) => {
let arr3 = [];
for (let i = 0; i < arr1.length; i++) {
if (arr2.indexOf(arr1[i]) === -1) {
arr3.push(arr1[i]);
}
}
for (let n = 0; n < arr2.length; n++) {
if (arr1.indexOf(arr2[n]) === -1) {
arr3.push(arr2[n]);
}
}
return arr3;
}
console.log(arrayDiffs([1, 44, 2, 3, 5], [33, 1, 2, 3, 4, 5]));
Have you tried sets in javassript. I think they are used for storing only unique elements.this will bring down you complexity to O(N), where N is total number of elements in arrays. Example :
const letters = new Set()
[...arr1,...arr2].filter(e=>!(arr1.includes(e)&&arr2.includes(e)))
var arr1 = [1, 44, 2, 3, 5],
arr2 = [33, 1, 2, 3, 4, 5],
arr3 = [...arr1,...arr2]
.filter(e=>!(arr1.includes(e)&&arr2.includes(e)));
console.log(arr3);
Related
A task:
Write a function that takes an array and a number n. Then output an array in which there are no elements that are repeated more than n times.
Example:
Input:
n = 3;
arr = [1, 2, 4, 4, 4, 2, 2, 2, 2]
Output:
result = [1, 2, 4, 4, 4, 2, 2]
Tried to do something like that, but it's not working correctly.
let arr = [1, 2, 4, 4, 4, 2, 2, 2, 2];
let new_set = [...new Set(arr)];
let result = [];
console.log(new_set); // [1, 2, 4]
first:
for (let i = 0; i < arr.length; i++) {
if (arr[i] === arr[i - 1]) {
continue first;
}
else {
let count = 0;
for (let j = i; j < arr.length; j++) {
if ((arr[i] === arr[j]) && (count < 3)) {
result.push(arr[j]);
}
}
}
}
You need a persistent outer variable that keeps track of how many times an item has been iterated over so far. Once past the limit, don't push the item being iterated over to the result.
const arr = [1, 2, 4, 4, 4, 2, 2, 2, 2]
let n = 3;
const counts = {};
const result = [];
for (const item of arr) {
counts[item] = (counts[item] || 0) + 1;
if (counts[item] <= n) {
result.push(item);
}
}
console.log(result);
Another option, if you want to use Array.reduce.
It's not as optimised as #CertainPerformance as it uses a filter inside a loop. But for small arrays like this unlikely to make much difference.
const arr = [1, 2, 4, 4, 4, 2, 2, 2, 2]
let n = 3;
const result = arr.reduce((a,v)=>(
a.filter(f=>f===v).length < n ?a.push(v):a,a),[]);
console.log(result);
Code golf version using reduce and without array.filter:
const f=(n,a)=>a.reduce((({c={},r=[]},i)=>
(c[i]??=0,++c[i]>n?0:r.push(i),{c,r})),{}).r;
console.log(f(3, [1, 2, 4, 4, 4, 2, 2, 2, 2]).join());
I have two arrays:
var array1= [1,3,5,7,9,11]
var array2= [undefined,4,6]
I need to merge one element of the array1, then one element of the array2, etc. This is my code:
function mergeArrays(array1, array2){
var array3 = [];
maxlength = Math.max(array1.length, array2.length);
for(i=0;i<maxlength;i++){
array3.push(array1[i]);
array3.push(array2[i]);
}
return console.log(array3);
}
The output now is:
array3 = [1,undefined,3,4,6,7,undefined,9,undefined,11,undefined]
I need the output to be:
array3 = [1,undefined,3,4,6,7,8,11]
I mean, I can't use ( != undefined), because if I have an undefined in the middle of the array it has to be there.
You are not placing a check for the length of shorter array.
Your function is fetching a value which is higher than the length of the array, hence, extra undefined. This should do the job
var array1 = [1, 3, 5, 7, 9, 11];
var array2 = [undefined, 4, 6];
function mergeArrays(array1, array2) {
var array3 = [];
maxlength = Math.max(array1.length, array2.length);
for (i = 0; i < maxlength; i++) {
if (i < array1.length) array3.push(array1[i]);
if (i < array2.length) array3.push(array2[i]);
}
return console.log(array3);
}
mergeArrays(array1, array2);
You can grab the max length of the two arrays and loop until you hit that value. While looping, check if the length has been exceeded and push onto the result.
const allEqual = (...args) =>
((head, ...tail) => tail.every(curr => curr === head))
(args.map(v => JSON.stringify(v)));
const test = ({ actual, expected }) => {
console.log(JSON.stringify(actual));
console.log(allEqual(actual, expected));
};
const interlaceArrays = (...arrays) => {
const result = [];
const maxLen = Math.max(...arrays.map(({ length }) => length));
for (let i = 0; i < maxLen; i++) {
arrays.forEach(arr => {
if (i < arr.length) result.push(arr[i]);
})
}
return result;
};
const
odd = [1, 3, 5, 7, 9, 11],
even = [undefined, 4, 6],
other = ['a', 'b'];
test({
actual: interlaceArrays(odd, even),
expected: [1, undefined, 3, 4, 5, 6, 7, 9, 11]
});
test({
actual: interlaceArrays(odd, even, other),
expected: [1, undefined, 'a', 3, 4, 'b', 5, 6, 7, 9, 11]
});
.as-console-wrapper { top: 0; max-height: 100% !important; }
I am trying to compare 2 arrays and return a new array with any items only found in one of the two given arrays.
So here is what I got:
function diffArray(arr1, arr2) {
var newArr = [];
var max;
var test;
(arr1.length > arr2.length) ? (max = arr1, test = arr2) : (max = arr2, test = arr1);
for (let i = 0; i < test.length; i++) {
if (max.indexOf(test[i]) === -1) {
newArr.push(test[i])
}
}
return newArr;
}
console.log(diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]));
However, when I run it, newArr returns an empty array. Can someone point out the error?
The error is that you are only checking the values in one array. You have to check for if values in arr1 are in arr2 and if values of arr2 are in arr1.
note: I added extra values to the arrays for testing
function diffArray(arr1, arr2) {
var newArr = [];
arr1.forEach(element => {
if(arr2.indexOf(element) === -1){
newArr.push(element)
}
});
arr2.forEach(element => {
if(arr1.indexOf(element) === -1){
newArr.push(element)
}
});
return newArr
}
console.log(diffArray([1, 2, 3,6, 5,7], [1, 2, 3, 4,10,23,11,123, 5]));
console.log(diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]));
function diffArray(arr1, arr2) {
var newArr = [];
let checkArr = [];
for (const val of arr1) {
checkArr[val] = 0
}
for (const val of arr2) {
checkArr[val] = checkArr[val] !== undefined ? checkArr[val] + 1 : 0
}
for (const val of arr1) {
if (checkArr[val] === 0) {
newArr.push(val)
}
}
for (const val of arr2) {
if (checkArr[val] === 0) {
newArr.push(val)
}
}
return newArr;
}
console.log(diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]));
So I want to create a function in js which takes two arrays and compare them and give a score depending on how many spots in the two arrays match. Is it right or it's bd written. I am new on coding.
Another problem I have is when I try to execute it on chrome's console. It says that compare is not defined
let score = 0;
function compare(arr1, arr2) {
for (let i = 0; i < arr2.length; i++) {
for (let j = 0; j < arr1.length; j++) {
if(arr1[j] === arr2[i]){
score++;
}
}
}
You can use .reduce() to find count of matched elements:
let arr1 = [1, 2, 3, 4, 5],
arr2 = [3, 4, 5, 6, 7],
compare = (a1, a2) => arr1.reduce((a, c) => a + arr2.includes(c), 0);
console.log(compare(arr1, arr2));
Alternatively, you can use .filter() to find array of matched elements and use its length to determine the count.
let arr1 = [1, 2, 3, 4, 5],
arr2 = [3, 4, 5, 6, 7],
compare = (a1, a2) => arr1.filter(v => arr2.includes(v)).length;
console.log(compare(arr1, arr2));
Docs:
Array.prototype.reduce()
Array.prototype.includes()
Array.prototype.filter()
Arrow Functions
This should work for you:
Updated the code as required by you :
let arr1 = [1, 2, 3, 4];
let arr2 = [3,2,3,4,5];
function compare(arr1,arr2){
let count=0;
const max=arr1.length>arr2.length ? arr2.length : arr1.length;
for(var i=0;i<max;i++){
if(arr1[i]==arr2[i]){
count++;
}
}
return count;
}
console.log(compare(arr1,arr2));
I have array1 = [4, 5, 6, 7, 4, 5]; and array2 = [4, 5].
And I want to match array2 in array1 and to output the number of times it matched.
var array1 = [4, 5, 6, 7, 4, 5];
var array2 = [4, 5];
function match(a1, a2) {
//matches 4,5 twice bc it is in array1
}
match(array1, array2) //output: 2;
You have to use a nested loop and compare each index of both arrays with each other.
var count = 0;
for (var i = 0; i < a1.length; i++)
{
for (var j = 0; j < a2.length; j++)
{
if (a1[i]==a2[j])
{
count +=1;
}
}
}
The best way to solve your problem is by intersection.
The solution for your problem: https://stackoverflow.com/a/1885660/4120554
What you're asking for is called an intersection. If you're only interested in the number of matches, this function should do the trick:
var array1 = [4, 5, 6, 7, 4, 5];
var array2 = [4, 5];
function intersectCount(arr1, arr2) {
var c = 0;
for(const item of arr2) {
if (arr1.indexOf(item) != -1) c++;
}
return c;
}
intersectCount(array1, array2); // result: 2
You can use below code for your question;
var array1 = [4, 5, 6, 7, 4, 5];
var array2 = [4, 5];
function match(a1, a2) {
var result = [];
for(const item of a2) {
if (a1.indexOf(item) > -1 ) {
result.push (item);
}
}
return result.length;
}
If you want to compare each index:
var match = (arr1,arr2)=>arr1.filter((el,i)=>el === arr2[i]).length;
If you want to count all elements that exist in both arrays, may unify one through a set:
function match(arr1,arr2){
var set = new Set( arr2 );
return arr1.filter( el => set.has(el) ).length;
}