Order Difference in javascript array of strings - javascript

Is there an easy way of getting an order difference of two string arrays?
var A = ['a', 'b'];
var B = ['b', 'a'];
by comparing these two is there an easy way of finding out that they swapped index? i couldnt find anything helpful online and
i dont really want to go the long and hard way about it as the array i am using is quite big. Using dragtable to reorder columns of my datatable and i am constantly pushing data to it so whenever an order changes i want the specific data to go into their designated column that is why i need it, thanks!

You could iterate over one array and compare the index of the current value to the index of same value in the other given array. If both mismatch, you can create map, containing a mismatch matrix for every value which you can use for further computation. See https://jsfiddle.net/f2jL46ke/
const arr1 = ['a', 'b', 'c']
const arr2 = ['b', 'c', 'a']
// I am assuming, that both arrays have an equal length
const differences = arr1.reduce((store, value) => {
const arr1Index = arr1.indexOf(value)
const arr2Index = arr2.indexOf(value)
if(arr1Index !== arr2Index) {
store[value] = [arr1Index, arr2Index]
}
return store
}, {})
console.log(differences)
With that approach you know A) what strings weren't at the same position in the arrays and B) where they are located in both arrays.

You will simply use sort() method
var A = ['a', 'b'];
var B = ['b', 'a'];
B=B.sort();
and B.sort() retutn ['a', 'b'];

Related

Filter javascript multidimensional array for values that exist at every index [duplicate]

This question already has answers here:
Array intersection (set-theoretic) with Array.prototype.reduce
(3 answers)
Closed 1 year ago.
Let's say that I have the following multidimensional array :
const arrayOfValues = [
['a', 'b', 'c'],
['a', 'c'],
['c']
];
I would like to create a new array containing only the values that are present at every index of my original multidimensional array. So I would end up with the following array in this case :
['c']
I'm having trouble finding a way to do so as I am not too familiar with javascript. I'm guessing I have to apply some sort of filtering (probably map over the array and apply a specific condition) but I'm not sure how to go about it.
You can use Array#reduce along with Array#filter.
const arr = [
['a', 'b', 'c'],
['a', 'c'],
['c']
];
let res = arr.reduce((acc,curr)=>acc.filter(x=>curr.includes(x)));
console.log(res);
Start with a persistent variable that starts with the values in the first subarray. Then iterate over each other subarray, reassigning that variable to a filtered version of the subarray currently being iterated over, filtering by whether the item is contained both in the previous subarray and the current one:
const arrayOfValues = [
['a', 'b', 'c'],
['a', 'c'],
['c']
];
let previous = arrayOfValues[0];
arrayOfValues.slice(1).forEach((subarr) => {
previous = subarr.filter(
item => previous.includes(item)
);
});
console.log(previous);

Rotate the elements of an array

I am trying to solve a javascript challenge from jshero.net. The challenge is this:
Write a function rotate that rotates the elements of an array. All
elements should be moved one position to the left. The 0th element
should be placed at the end of the array. The rotated array should be
returned. rotate(['a', 'b', 'c']) should return ['b', 'c', 'a'].
All I could come up with was this :
function rotate(a){
let myPush = a.push();
let myShift = a.shift(myPush);
let myFinalS = [myPush, myShift]
return myFinalS
}
But the error message I got was:
rotate(['a', 'b', 'c']) does not return [ 'b', 'c', 'a' ], but [ 3,
'a' ]. Test-Error! Correct the error and re-run the tests!
I feel like I'm missing something really simple but I can't figure out what. Do you guys have other ways to solve this?
function rotate(array){
let firstElement = array.shift();
array.push(firstElement);
return array;
}
To achieve the output you are looking for, first you have to use Array.shift() to remove the first element, then using Array.push() add the element back to the end of the Array, then return the array, the issue is that you used the wrong oder for these steps, also .push() method takes element to be added as argument, here is a working snippet:
function rotate(a){
let myShift = a.shift();
a.push(myShift);
return a;
}
console.log(rotate(['a', 'b', 'c']));
Here I have created a utility where, the input array will not get mutated even after rotating the array as per the requirement.
function rotate(a){
let inputCopy = [...a]
let myShift = inputCopy.shift();
let myFinalS = [...inputCopy, myShift]
return myFinalS
}
console.log(rotate([1,2,3]))
console.log(rotate(["a","b","c"]))
Hope this helps.
function rotate(arr){
let toBeLast = arr[0];
arr.splice(0, 1);
arr.push(toBeLast);
return arr;
}
console.log(rotate(['a', 'b', 'c']));
New to stack overflow. Hope this helps :)
arr.unshift(...arr.splice(arr.indexOf(k)))
Using unshift(), splice() and indexOf(), this is a one line that should help. arr is the array you want to rotate and k the item you want as first element of the array. An example of function could be:
let rotate = function(k, arr) {
arr.unshift(...arr.splice(arr.indexOf(k)))
}
And this are examples of usage:
let array = ['a', 'b', 'c', 'd']
let item = 'c'
rotate(item, array)
console.log(array)
// > Array ["c", "d", "a", "b"]
Finally back to the original array:
rotate('a', array)
console.log(array)
// > Array ["a", "b", "c", "d"]

Can't figure out the given native alternative code performing a certain tasks

Can't figure out the given native alternative code performing a certain tasks of creating an array of elements split into groups of the given size argument.
With lodash I've solve this task using _.chunk, but there are two versions of it on the documentation, one is with lodash and the other one is native JavaScript.
I'm interested in the native version and I've started to decipher it but I can't figure it out. I know how reduce works but the conditional part is where I got stuck. I understand if the condition is true it will return a certain value but its still not clear to me particularly the returned value with bracket notation, if someone can explain on detail will be much appreciated.
// Lodash
_.chunk(['a', 'b', 'c', 'd'], 3); // This one is solve
// => [['a', 'b', 'c'], ['d']]
// Native
const chunk = (input, size) => {
return input.reduce((arr, item, idx) => {
return idx % size === 0 // This entire part of conditional is not clear
? [...arr, [item]]
: [...arr.slice(0, -1), [...arr.slice(-1)[0], item]];
}, []);
};
chunk(['a', 'b', 'c', 'd'], 3);
// => [['a', 'b', 'c'], ['d']]
All the code is doing is that
Creating an empty array.
It creates another nested empty array [] inside that array.
It adds each element to that nested array each time.
If the index is multiple of 3 it adds another nested array and keep on add the elements to it
The easier version to understand is.
const chunk = (input, size) => {
return input.reduce((arr, item, idx) => {
if(idx % size === 0){
//The previous nested arrays
let previous = arr;
//Adds a new nested array with current element
let newArr = [item];
//concentrate both and return
return arr.concat([newArr]);
}
else{
//This is part of array which concatin all nested arrays expect the last one
let allExepctLast = arr.slice(0, -1);
//this is last nested array
let last = arr.slice(-1)[0];
//Add the current element to the end of last nested array.
let addedValue = [...last,item]
return [...allExepctLast ,addedValue]
}
}, []);
};
console.log(chunk(['a', 'b', 'c', 'd'], 3));
Explanation with example.
Consider the above array ['a', 'b', 'c', 'd']
The arr is initialized as empty array [].
idx = 0 and item = 'a'
When idx is 0 then the condition idx % size === 0 is true so the returned value will be.
[...arr, [item]]
The arr is empty so spreading it will get nothing. [item] will be ['a']. So the whole arr becomes
[['a']]
idx = 1 and item = 'b'
This time the condition idx % size is false so the value returned will be
[...arr.slice(0, -1), [...arr.slice(-1)[0], item]]
arr.slice(0,-1) will be empty array so spreading it will be nothing.
arr.slice(-1)[0] will get last nested array ['a'] and will add item at its end. So it become ['a','b']. So the arr becomes [['a','b']]
idx = 2 and item = 'c'
Same will happen as happened for idx = 1 The final array will become.
[['a','b',c]]
idx = 3 and item = 'd'
Now the first condition is true so the [...arr, [item]] will be returned.
...arr will generate the first nested array ['a','b','c'] and [item] will be ['d'] Both wrapped in [] will give
[['a','b','c'], ['d']]

create two differents variables from the same array [duplicate]

This question already has answers here:
Copy array by value
(39 answers)
Closed 3 years ago.
I've an array, and I want to create 2 differents variables from the same array but this variables must have different result. For example, an array of string : the first variable must contain this array, and the other variable must contains this values but sorted. But it's not working :
var letters = ['b', 'c', 'a']; // datas
const lettersUnsorted = letters; // i want the array like the var "letters"
const letterSorted = letters.sort(); // i want the array like the var "letters" but sorted
console.log(letterSorted); // OK => returns: ["a", "b", "c"]
console.log(lettersUnsorted); // KO => returns: ["a", "b", "c"] instead of ['b', 'c', 'a']
You should make a copy the array first because sort() method modifies the original array. You can make the copy of the array using slice()
var letters = ['b', 'c', 'a'];
const lettersUnsorted = letters;
const letterSorted = letters.slice().sort(); //this line is changed
console.log(letterSorted);
console.log(lettersUnsorted);
This is because the reference to the original letters array is maintained.
lettersUnsorted and letterSorted are both referencing to the letters variable. This is because letters is an array (which is technically an object), and in JavaScript, assigning another variable to it will result in assignment by reference (rather than assignment by value). Therefore, any operations or mutation to letters will result in both lettersUnsorted and letterSorted in having the same result as letters, due to the reference to letter.
You should create a shallow clone of the original letters array. This will allow you to safely carry out any mutation without affecting the other array. We can achieve this using ES6's spread syntax.
const letters = ['b', 'c', 'a'];
const lettersClone = [...letters].sort();
console.log(letters);
console.log(lettersClone);
you can use concat also.
var letters = ['b', 'c', 'a'];
const lettersUnsorted = letters;
const letterssorted = ([].concat(letters)).sort();

Push and remove duplicates of array

I have an array (or Set?) of arr = ['a', 'b', 'c'] and I want to add d to it, which could be done with arr.push('d').
But I only want unique values in the array, and I want the latest values added to be in the front of the array.
So if I first add d the array should become ['d', 'a', 'b', 'c'] and if I now add b the array should become ['b', 'd', 'a', 'c'] etc.
Should it be something like
function addElement(arr, element) {
if (arr.includes(element)) {
arr.splice(arr.indexOf(element, 1));
}
arr.unshift(element);
}
I guess this could be done with Sets, since sets can only contain unique values.
You could use a Set and delete the item in advance and add it then. To get the wanted order, you need to reverse the rendered array.
function addToSet(v, set) {
set.delete(v);
set.add(v);
}
var set = new Set;
addToSet('d', set);
addToSet('c', set);
addToSet('b', set),
addToSet('a', set);
addToSet('d', set);
console.log([...set].reverse());
var val = 'c';
var arr = ['a','b'];
if($.inArray( val, arr ) ==-1){
// value dosend exit
arr.unshift(val);
} else {
console.log('value already there')
}
console.log(arr);
$.inArray() work similar to indexOf() method. It searches the element in an array, if it’s found then it return it’s index.
http://webrewrite.com/check-value-exist-array-javascriptjquery/
your function works just you have to adjust with a small fix
arr.splice(arr.indexOf(element),1);
var arr = ['a', 'b', 'c'] ;
function addElement(arr, element) {
if (arr.includes(element)) {
arr.splice(arr.indexOf(element),1);
}
arr.unshift(element);
}
addElement(arr,'d');
addElement(arr,'b');
console.log(arr);
Especially for those who don't like .unshift() performance This would be another way of doing this job;
function funky(a,e){
var ix = a.indexOf(e);
return (~ix ? a.splice(ix,0,...a.splice(0,ix))
: a.splice(0,0,e),a);
}
var a = ['d', 'a', 'b', 'c'];
console.log(funky(a,'z'));
console.log(funky(a,'d'));
console.log(funky(a,'c'));
console.log(funky(a,'f'));

Categories

Resources