Performing Set calculations in javascript array - javascript

I have 2 arrays lets say:
A = [1,2,3,4,5] and B = [1,2,3,6,7]
and I'd like to perform the following 'set calculations':
C = (A ∩ B)
D = A - (A ∩ B)
E = B - (A ∩ B)
Essentially:
C = [1,2,3]
D = [4,5]
E = [6,7]
Is there a smart way to do this or am I going to have to cross check each array member with loops and ifs? I cannot use an external library (like math.js or w/e).
Thanks in advance.

filter() can at least hide the loops for you:
A = [1,2,3,4,5];
B = [1,2,3,6,7];
C = intersection(A, B);
D = arrayDiff(A, C);
E = arrayDiff(B, C);
console.log(JSON.stringify(C));
console.log(JSON.stringify(D));
console.log(JSON.stringify(E));
function intersection(a, b) {
return a.filter(
function(el) {
return b.indexOf(el) >= 0;
}
);
}
function arrayDiff(a, b) {
return a.filter(
function(el) {
return b.indexOf(el) < 0;
}
);
}

As of ES6, Javascript has an inbuilt set object, which offers neat ways to do the above operations.
var intersection = function(setA, setB){
return new Set([x for (x of setA) if (setB.has(x))]);
}
var difference = function(setA, setB){
return new Set([x for (x of setA) if (!setB.has(x))]);
}
A = new Set([1,2,3,4,5]);
B = new Set([1,2,3,6,7]);
// A ∩ B = ([1,2,3])
intersection(A, B);
// A \ B = ([4,5])
difference(A, B);
// B \ A = ([6,7])
difference(B, A);

Related

How to return the name of the variable with maximum value from an array using Javascript

I have been trying to return a instead of 100 in Javascript?
However, I believe I am doing something wrong with my loop.
let a = 100
let b = 25
let c = 75
let d = 50
let A = [a,b,c,d]
function solution(A) {
// write your code in JavaScript (Node.js 8.9.4)
let result = []
let max = Math.max(...A)
for (let i = 0; i < A.length; i++)
if (A[i] === max){
return A[i]
}
return A
}
console.log( solution(A))
As #user1599011 mentioned, this is not possible using an array as your example.
I'd recommend using an object, with the key's as desired, and the value as the integer. We can use the the shorthand object syntax to create the object like so:
let A = { a, b, c, d };
Then you can use reduce() on Object.keys() to search for the key with the heights value:
let a = 100
let b = 25
let c = 75
let d = 50
let A = { a, b, c, d };
function solution(A) {
return Object.keys(A).reduce((prev, cur) => A[prev] > A[cur] ? prev : cur);
}
console.log(solution(A)); // a
As has been pointed out, use an object. Pass that object to solution(); one way you can find and return the key of the highest value is to use Object.entries() to produce an array with [key, value], e.g., [a,100], as elements, sort by value in descending order then return the key of element in index 0.
let a = 100;
let b = 25;
let c = 75;
let d = 50;
let A = {a,b,c,d};
function solution(A) {
return Object.entries(A).sort((a, b) => b[1] - a[1])[0][0]
}
console.log( solution(A) )
Note: If there are multiple keys with the highest value, this will return only one key.

Why can't I swap 2 variables in JavaScript?

I am trying to swap two variables in JavaScript, but my code does not work. Can anyone tell me why?
This should return 10, 5 I think, because I already called the swap function. But instead, it returns 5, 10.
function swap(a, b) {
var temp = a;
a = b;
b = temp
}
var x = 5;
var y = 10;
swap(x, y);
console.log(x, y);
JavaScript, like Java, is pass by reference only. This means that while your function does swap the values, the actual values of x and y in the calling scope have not been swapped. One workaround here might be to return an array of values, swapped:
function swap(a, b) {
return [b, a];
}
var x = 5;
var y = 10;
[x, y] = swap(x, y);
console.log("x after swap = " + x);
console.log("y after swap = " + y);
Note that here the critical line is the assignment:
[x, y] = swap(x, y);
This reassigns x and y to the swapped array in one line.
You can use Destructuring assignment method:
let a = 1;
let b = 2;
[a, b] = [b, a];
a; // => 2
b; // => 1
Javascript function values aren't passed by reference, instead values get copied in a,b. So instead return values:
function swap(a, b) {
return [b, a];
}
Later get it:
[x, y] = swap(x, y);
You can achieve this using JavaScript's objects, which passed by sharing, similar to pass by reference you may have experienced in other languages. This allows you to do a few things that are not possible with primtive values -
function ref (value) {
return { value }
}
function deref (t) {
return t.value
}
function set (t, value) {
t.value = value
}
function swap (a, b) {
const temp = deref(a)
set(a, deref(b))
set(b, temp)
}
const x = ref(3)
const y = ref(5)
swap(x,y)
console.log(deref(x), deref(y)) // 5 3
You can make this abstraction in any way you choose -
const box = v => [v]
const unbox = t => t[0]
const set = (t, v) => t[0] = v
function swap (a, b) {
const temp = unbox(a)
set(a, unbox(b))
set(b, temp)
}
const x = box(3)
const y = box(5)
swap(x,y)
console.log(unbox(x), unbox(y)) // 5 3

how to switch value from variable using function

function switchValue (a, b) {
return [b,a] = [a,b]
}
var a = 'computer'
var b = 'laptop'
switchValue(a, b)
console.log("a = " +a)
console.log("b = " +b)
how to change this variable, that output :
a = laptop
b = komputer
please help me
Try this
function switchValue(a, b) {
let c = a;
let a = b;
let b = c;
return [a, b];
}
You can do it like this but generally it's not advisable to use global variables
var a = 'computer'
var b = 'laptop'
function switchValue (val1, val2) {
let c = val1;
a = val2;
b = c;
}
switchValue(a, b)
console.log("a = " + a);
console.log("b = " + b);
Without global variables
function switchValue (a, b) { return [b,a] }
var a = 'computer'
var b = 'laptop'
let [A,B] = [...switchValue(a, b)]
console.log("a = " + A);
console.log("b = " + B);

how to call same function with different parameter in javascript?

function partialize(){
}
function calculation(a,b,c){
console.log(a*b/c);
return a*b/c;
}
var a = 10, b= 20, c= 5;
var partialize1 = partialize(calculation, a);
partialize1(b,c)
var partialize2 = partialize(calculation, a, b);
partialize2(c)
var partialize3 = partialize(calculation, a, b, c);
partialize3()
I need to write partialize function which give same output in all three condition.
I tried like that it work .but i used spread operator .can we do this without spread operator ?
function partialize(fn,...a) {
console.log(...a);
return function (...b) {
console.log(...b);
fn(...a,...b);
}
}
function calculation(a, b, c) {
console.log(a * b / c);
return a * b / c;
}
var a = 10, b = 20, c = 5;
var partialize1 = partialize(calculation, a);
partialize1(b, c)
var partialize2 = partialize(calculation, a, b);
partialize2(c)
var partialize3 = partialize(calculation, a, b, c);
partialize3()
can we do the same thing without spread operator ?
You can save the initial arguments that were passed and return a function that can be called with the rest of the arguments, then calling the original function with apply:
function partialize(fn) {
const initialArguments = Array.from(arguments).slice(1);
return function() {
const finalArguments = Array.from(arguments);
fn.apply(null, initialArguments.concat(finalArguments));
}
}
function calculation(a, b, c) {
console.log(a * b / c);
return a * b / c;
}
var a = 10,
b = 20,
c = 5;
var partialize1 = partialize(calculation, a);
partialize1(b, c)
var partialize2 = partialize(calculation, a, b);
partialize2(c)
var partialize3 = partialize(calculation, a, b, c);
partialize3()
If your code is currently working as is but you'd like to change it to not use the spread operator, you can use the arguments object instead.
arguments object:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments
Also check out this stackoverflow question for some example code working with the arguments object if helpful. How can I convert the "arguments" object to an array in JavaScript?
user944513, to simulate an overload of methods in javascript, yo can use the arguments object, which comes by default in the functions. To explain you better, i've written a block of code. Hope this can help you:
function suma(a = 0){
let resultado = 0;
console.log(arguments.length);
for(let i = 0; i < arguments.length; i++)
{
if(typeof(arguments[i] == "number")){
resultado += arguments[i];
}
}
}
suma(1,2,3,4); // 10
suma(1,2) // 3

How to merge arrays?

How to merge these two arrays using JavaScript:
[{"id1":"value1","id2":"value2"}]
[{"id3":"value3","id4":"value4"}]
Into this:
[{"id1":"value1","id2":"value2","id3":"value3","id4":"value4"}]
You can use a simple function.
Either by adding the key/values from b into a:
function merge(a, b) {
for (var p in b[0]) {
a[0][p] = b[0][p];
}
return a;
}
merge(a, b);
Or by using a native array function like reduce:
function merge2(a, b) {
return b.reduce(function (el) {
return el;
}, a);
}
console.log(merge2(a, b));
DEMO
Just use the built-in Javascript Array .concat() method.
http://www.w3schools.com/jsref/jsref_concat_array.asp
var a = ["id1","value1","id2","value2"]
var b = ["id3","value3","id4","value4"]
var c = a.concat(b)
//c is now ["id1","value1","id2","value2","id3","value3","id4","value4"]

Categories