Optimising ES6 intersection of Arrays function [duplicate] - javascript

This question already has answers here:
How to get the difference between two arrays in JavaScript?
(84 answers)
Closed 5 years ago.
I have the following Arrays:
this.originalSelectedRows = [1,2,3,4,5];
this.selectedRows = [3,4,5,6,7,8];
I want to know the following:
How many numbers are in this.originalSelectedRows, but not in this.selectedRows
Which in this case would be 2:
1 and 2
and how many numbers are in this.selectedRows, but not this.originalSelectedRows
Which in this case would be 3:
6, 7 and 8
I have the following, which works fine:
let isOnListCount = 0;
let isNotOnListCount = 0
this.selectedRows.map((row) => {
const isSelected = this.originalSelectedRows.filter(x => x === row);
if(isSelected.length > 0)
isOnListCount++;
else
isNotOnListCount++;
});
But I want to know if this can be achieved in a neater fashion usng some of ES6's new features, or original JS

You could take the length as counter and reduce the value with common items.
var array1 = [1, 2, 3, 4, 5],
array2 = [3, 4, 5, 6, 7, 8],
count1 = array1.length,
count2 = array2.length;
array1.forEach(function (a) {
if (array2.includes(a)) {
count1--;
count2--;
}
});
console.log(count1, count2);

Sets will do a great job here :)
let set1 = new Set(this.originalSelectedRows)
let set2 = new Set(this.selectedRows)
let difference = new Set([...set1].filter(n => !set2.has(n)))
They are also relatively fast as well, but not as fast as a specially crafted solution :P
I am assuming that all of your items are unique though :)

I'd convert one array into a set and than filter the other array for items which aren't in the set.
const
valuesA = [1,2,3,4,5],
valuesB = [3,4,5,6,7,8];
function getUniqueValues(sourceArray, testArray) {
const
set = new Set(testArray);
return sourceArray.filter(value => !set.has(value));
}
console.log(`Values in A and not in B: ${getUniqueValues(valuesA, valuesB)}`);
console.log(`Values in B and not in A: ${getUniqueValues(valuesB, valuesA)}`);

You can just use Array#includes function to check if the element exists in the second array or not
const originalSelectedRows = [1,2,3,4,5];
const selectedRows = [3,4,5,6,7,8];
let isOnListCount = 0;
let isNotOnListCount = 0;
selectedRows.forEach(row =>
originalSelectedRows.includes(row) ? isOnListCount++ : isNotOnListCount++
);
console.log(isOnListCount);
console.log(isNotOnListCount);

Related

change index in one array in accordance with another one js [duplicate]

This question already has answers here:
Sort two arrays the same way
(12 answers)
Closed 18 days ago.
I need to change indexes of elements in arr a due to their indexes in arr b.
const a = [4,3,2,1,5];
const b = [1,2,3,4,5];
console.log(a) [1,2,3,4,5]
If you mean ordering array a according to array b, then you can do like this:
a.forEach((element,i) => {
// first get the index of a[i] from array b
const index = b.indexOf(a[i])
// then swap them
const temp = a[index];
a[index] = a[i];
a[i] = temp;
})
You could sort by using the other array as index. If this daoes not work with real data, please andd a small amount of data to highlight the problem.
const
a = [4, 3, 2, 1, 5],
b = [1, 2, 3, 4, 5];
a.sort((l, r) => b[l - 1] - b[r - 1]);
console.log(...a);

How to update a specific index of an array when using spread operator [duplicate]

This question already has answers here:
Replace element at specific position in an array without mutating it
(9 answers)
Closed 2 years ago.
Consider an array as
const foo = [1, 2, 3];
Now if I want to replace the second element I can just do:
foo[1] = 4; or
foo.splice(1,1,4); or
const foo = [1, 2, 3];
console.log([...foo.slice(0, 1), 4, ...foo.slice(2)]);
// I know this creates a new array unlike the above two ways.
but when we use spread operator for shallow copying objects we can dynamically overwrite a property like:
const someObject = {
a: 1,
b: 2,
c: 3
}
const propertyToChange = 'b';
const newObject = { ...someObject, [propertyToChange]: 4 };
So, is there an equivalent of this for arrays? Maybe something like the following to change an element based on the index.
const newArray = [...oldArray, [dynamicIndex]: 4 ];
Sort of: you can use Object.assign:
const newArray = Object.assign([...oldArray], {[dynamicIndex]: 4});
// Or
const newArray = Object.assign([], oldArray, {[dynamicIndex]: 4});
That works because arrays are objects.
Live Example:
const oldArray = [1, 2, 3, 4, 5, 6];
const dynamicIndex = 3; // The fourth entry
const newArray = Object.assign([], oldArray, {[dynamicIndex]: "four"});
console.log(newArray);

Sort object based on value highest to lowest [duplicate]

This question already has answers here:
Sorting object property by values
(44 answers)
Closed 3 years ago.
I'm trying to sort an object and rebuild it based on highest to lowest values in Javascript. I've built a function which takes an array of numbers, counts them adds them up and then creates an object, my function for sorting doesn't seem to be working correctly,
const numbersToCount = [10, 10, 10, 5, 4, 3, 2, 2, 1]
function sort () {
var counts = {}
for (var i = 0; i < numbersToCount.length; i++) {
var num = numbersToCount[i];
counts[num] = counts[num] ? counts[num] + 1 : 1;
}
var numbersToSort = []
for (var sort in counts) {
numbersToSort.push([sort , counts[sort]])
}
numbersToSort.sort((a, b) => {
return a[1] - b[1]
})
counts = {}
numbersToSort.forEach((item) => {
counts[item[0]]=item[1]
})
console.log(counts)
}
Currently, counts would output initally:
{
'1': 1,
'2': 2,
'3': 1,
'4': 1,
'5': 1,
'10': 3
}
Object property iteration has separate rules for properties that look like array indexes: in that case they are always ordered in numerical, ascending order.
A quick fix is to agree with yourself to have those properties prefixed with some non-digit character, like an underscore:
Change:
counts[item[0]] =
to:
counts["_" + item[0]] =
Most would advise against using plain objects for keeping a certain order. Alternatively, use a Map, which always sticks to insertion order:
counts = new Map(numbersToSort);
const numbersToCount = [10, 10, 10, 5, 4, 3, 2, 2, 1];
const distinctNumbersToCount = [...new Set(numbersToCount)];
const sortNumbersToCount = distinctNumbersToCount.sort((a, b) => a - b);
const response = sortNumbersToCount.map((number, index) =>{
return { [index]: number }
})
console.log(response);
Output should be:

How to take every 3rd element of an array [duplicate]

This question already has answers here:
Javascript: take every nth Element of Array
(6 answers)
Closed 6 years ago.
I have an array, and want to return only every third element as a new array (starting at 0).
For example:
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
let newArr = [1, 4, 7];
This is the way I am currently doing this:
let newArr = [];
for(let x = 0; x < arr.length; x += 3) {
newArr.push(arr[x]);
}
return newArr;
Is there a way to do this with arr.map? Is there just an easier way to do this?
You can alternatively do it with a filter,
let newArr = arr.filter((_,i) => i % 3 == 0);
But remember, using basic for loop is bit more efficient than others in some contexts.

How to compare to different arrays in javascript/jquery and get back the columns with difference in an array

Since I don't know how this works very well and other questions such as:
How to compare arrays in JavaScript?
or, JavaScript array difference
are completely different questions and after 1 and a half hours of scouring the web no results I am going to go and ask this question simply. Say you have two arrays [1,2,3] and [1,4,1]. Then how would you get a program to make our variable (say x) to be [1,2] (because column 1 and 2 are different if you count the first column as column 0)?
Please see this:
var array1 = [1, 2, 3];
var array2 = [1, 4, 1];
var columndiff = [];
for (i = 0; i < array1.length; i++) {
if (array1[i] != array2[i])
columndiff.push(i);
}
console.log(columndiff);
Note: Here we are assuming that array1 and array2 has equal length
ES2015 code:
const a = [1, 2, 3];
const b = [1, 4, 1];
const result = a.reduce((res, val, index) => {
if (val !== b[index]) res.push(index);
return res;
}, []);
console.log(result); // [1, 2]
You can simply do like this;
var arr = [1,3,4,5,2,3],
brr = [1,3,5,5,1,2],
res = arr.reduce((p,c,i) => c !== brr[i] ? p.concat(i) : p,[]);
console.log(res);

Categories

Resources