Related
I am merging two sorted arrays in JavaScript. When I call function with two arrays having numbers it works fine, but when I call that function with strings then it does not work. Why?
function mergeSortedArrays(array1, array2) {
const mergedArray = [];
let array1Item = array1[0];
let array2Item = array2[0];
let i = 1;
let j = 1;
if (array1.length === 0) {
return array2;
}
if (array2.length === 0) {
return array1;
}
while (array1Item || array2Item) {
if (array2Item === undefined || array1Item < array2Item) {
mergedArray.push(array1Item);
array1Item = array1[i];
i++;
} else {
mergedArray.push(array2Item);
array2Item = array2[j];
j++;
}
}
console.log(mergedArray);
}
//working?
mergeSortedArrays([0, 3, 4, 12, 222], [3, 4, 6, 30]);
// not working why?
mergeSortedArrays(["0", "3", "4", "12", "222"], ["3", "4", "6", "30"]);
As said in the comments, strings in JS are compared lexically , so, "222" is smaller than "3".
A solution that I see that you can use, is this one:
After checking the arrays for nullity, then concat then into mergedArray, then use the JS function sort(), with the basic return of value1 - value2, that way it will sort the strings in the order you want, and also will work for numbers.
(Further read: Why is one string greater than the other when comparing strings in JavaScript?)
function mergeSortedArrays(array1, array2) {
let mergedArray = [];
if (array1.length === 0) {
return array2;
}
if (array2.length === 0) {
return array1;
}
mergedArray = array1.concat(array2)
mergedArray.sort(function(a, b) {
return a - b
})
console.log(mergedArray);
return mergedArray;
}
mergeSortedArrays([0, 3, 4, 12, 222], [3, 4, 6, 30]);
mergeSortedArrays(["0", "3", "4", "12", "222"], ["3", "4", "6", "30"]);
BUT, be knowing that this solution will only work as expected if the strings are representations of numbers ("1", "2",...), if it is something like "aa", "abc", "b" it probably won't work well and another solution may be needed. (something like this: https://stackoverflow.com/a/51169/8732818)
Sort for string works differently than numbers. Its based on the ASCII table values. For example "99" > "100000" return should return true
For an array like:
["abc", "bc", "dd", "d", "ee", "ff", "e"]
What would be an efficient way to get:
[["abc", "bc"],["dd", "d"],["ee", "e"]]
Explanation
["abc", "bc"] because "abc" contains "bc"
["dd", "d"] because "dd" contains "d"
["ee", "e"] because "ee" contains "e"
Any new method including parallelism is also welcomed.
You can do it using reduce(). Check if the element is included by other element. If not then add it as key of accumulator. If its included then add it to that array. At last use Object.values() to get values(arrays). Use filter() to remove arrays having length = 1
let arr = ["abc", "bc", "dd", "d", "ee", "ff", "e"]
let res = Object.values(arr.reduce((ac,a,i) => {
if(!arr.some((x,b) => x.includes(a) && i !== b)) ac[a] = [a];
else {
for(let k in ac){
if(k.includes(a)){
ac[k].push(a)
break;
}
}
}
return ac;
},{})).filter(x => x.length -1)
console.log(res)
You can loop in reverse direction and using the function splice you can drop the element and push it into the current array.
let arr = ["abc", "bc", "dd", "d", "ee", "ff", "e"];
let result = [];
for (let i = arr.length - 1; i >= 0; i--) {
let target = arr.splice(i, 1).pop();
if (target === undefined) continue;
let current = [target],
index = 0;
while ((index = arr.findIndex(s => s.includes(target))) != -1) {
current.push(arr[index]);
arr.splice(index, 1);
}
if (current.length > 1) result.push(current);
}
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
My array contains list of the Arabic and roman numbers as string. I would like to sort them by the order of Roman numbers ascending first then follows the Arabic numbers in ascending order.
I write the code as below,
var myarray = ["i", "ii", "iii", "xv", "x", "1", "2", "3", "5", "601", "vi", "vii", "88", "99", "201", "101", "xix", "125", "iv", "vi", "v", "xiv", "58"]
myarray.sort(function (a, b) {
try {
if (Number(a) != null)
a = Number(a);
if (Number(b) != null)
b = Number(b);
} catch (e) {}
if (a > b) {
return 1;
}
if (b > a) {
return -1;
}
if (a == b) {
return a.position - b.position;
}
});
console.log(myarray);
But the results are like,
Results: ii,iii,xv,x,1,2,3,5,v,vi,vii,vi,iv,xix,xiv,58,88,99,101,125,201,601,i
If I have not convert the string to numbers,
Results: 1,101,125,2,201,3,5,58,601,88,99,i,ii,iii,iv,v,vi,vi,vii,x,xiv,xix,xv
My expect result should be
Results: i,ii,iii,iv,v,vi,vi,vii,x,xiv,xv,xix,1, 2, 3,5,58,88,99,101,125,201,601
Multiple things here:
You don't need a try / catch block. Just leave it.
Checking the parsed number for null won't give you the expected result. You need to check for NaN.
Either parse both values to a number or none. Otherwise you can't compare properly.
Usually numbers will be returned before strings. To avoid this behaviour you need to invert the result value by multiplicating with -1, if one value is a number and one is a string.
Here is the working version of the sort method:
var myarray = ["i", "ii", "iii", "xv", "x", "1", "2", "3", "5", "601", "vi", "vii", "88", "99", "201", "101", "xix", "125", "iv", "vi", "v", "xiv", "58"]
myarray.sort(function (a, b) {
if (!isNaN(Number(a)) && !isNaN(Number(b))) {
a = Number(a);
b = Number(b);
}
var result;
if (a > b) {
result = 1;
}
if (b > a) {
result = -1;
}
if (a == b) {
result = a.position - b.position;
}
if (isNaN(Number(a)) !== isNaN(Number(b))) {
result = result * -1;
}
return result;
});
console.log(myarray);
I have JS array with strings, for example:
var strArray = [ "q", "w", "w", "e", "i", "u", "r"];
I need to compare for duplicate strings inside array, and if duplicate string exists, there should be alert box pointing to that string.
I was trying to compare it with for loop, but I don't know how to write code so that array checks its own strings for duplicates, without already pre-determined string to compare.
The findDuplicates function (below) compares index of all items in array with index of first occurrence of same item. If indexes are not same returns it as duplicate.
let strArray = [ "q", "w", "w", "w", "e", "i", "u", "r"];
let findDuplicates = arr => arr.filter((item, index) => arr.indexOf(item) != index)
console.log(findDuplicates(strArray)) // All duplicates
console.log([...new Set(findDuplicates(strArray))]) // Unique duplicates
Using ES6 features
Because each value in the Set has to be unique, the value equality will be checked.
function checkIfDuplicateExists(arr) {
return new Set(arr).size !== arr.length
}
var arr = ["a", "a", "b", "c"];
var arr1 = ["a", "b", "c"];
console.log(checkIfDuplicateExists(arr)); // true
console.log(checkIfDuplicateExists(arr1)); // false
var strArray = [ "q", "w", "w", "e", "i", "u", "r", "q"];
var alreadySeen = {};
strArray.forEach(function(str) {
if (alreadySeen[str])
console.log(str);
else
alreadySeen[str] = true;
});
I added another duplicate in there from your original just to show it would find a non-consecutive duplicate.
Updated version with arrow function:
const strArray = [ "q", "w", "w", "e", "i", "u", "r", "q"];
const alreadySeen = {};
strArray.forEach(str => alreadySeen[str] ? console.log(str) : alreadySeen[str] = true);
You could take a Set and filter to the values that have already been seen.
var array = ["q", "w", "w", "e", "i", "u", "r"],
seen = array.filter((s => v => s.has(v) || !s.add(v))(new Set));
console.log(seen);
Using some function on arrays:
If any item in the array has an index number from the beginning is not equals to index number from the end, then this item exists in the array more than once.
// vanilla js
function hasDuplicates(arr) {
return arr.some( function(item) {
return arr.indexOf(item) !== arr.lastIndexOf(item);
});
}
function hasDuplicates(arr) {
var counts = [];
for (var i = 0; i <= arr.length; i++) {
if (counts[arr[i]] === undefined) {
counts[arr[i]] = 1;
} else {
return true;
}
}
return false;
}
// [...]
var arr = [1, 1, 2, 3, 4];
if (hasDuplicates(arr)) {
alert('Error: you have duplicates values !')
}
Simple Javascript (if you don't know ES6)
function hasDuplicates(arr) {
var counts = [];
for (var i = 0; i <= arr.length; i++) {
if (counts[arr[i]] === undefined) {
counts[arr[i]] = 1;
} else {
return true;
}
}
return false;
}
// [...]
var arr = [1, 1, 2, 3, 4];
if (hasDuplicates(arr)) {
alert('Error: you have duplicates values !')
}
function hasDuplicateString(strings: string[]): boolean {
const table: { [key: string]: boolean} = {}
for (let string of strings) {
if (string in table) return true;
table[string] = true;
}
return false
}
Here the in operator is generally considered to be an 0(1) time lookup, since it's a hash table lookup.
var elems = ['f', 'a','b','f', 'c','d','e','f','c'];
elems.sort();
elems.forEach(function (value, index, arr){
let first_index = arr.indexOf(value);
let last_index = arr.lastIndexOf(value);
if(first_index !== last_index){
console.log('Duplicate item in array ' + value);
}else{
console.log('unique items in array ' + value);
}
});
You have to create an empty array then check each element of the given array if the new array already has the element it will alert you.
Something like this.
var strArray = [ "q", "w", "w", "e", "i", "u", "r"];
let newArray =[];
function check(arr){
for(let elements of arr){
if(newArray.includes(elements)){
alert(elements)
}
else{
newArray.push(elements);
}
}
return newArray.sort();
}
check(strArray);
Use object keys for good performance when you work with a big array (in that case, loop for each element and loop again to check duplicate will be very slowly).
var strArray = ["q", "w", "w", "e", "i", "u", "r"];
var counting = {};
strArray.forEach(function (str) {
counting[str] = (counting[str] || 0) + 1;
});
if (Object.keys(counting).length !== strArray.length) {
console.log("Has duplicates");
var str;
for (str in counting) {
if (counting.hasOwnProperty(str)) {
if (counting[str] > 1) {
console.log(str + " appears " + counting[str] + " times");
}
}
}
}
This is the simplest solution I guess :
function diffArray(arr1, arr2) {
return arr1
.concat(arr2)
.filter(item => !arr1.includes(item) || !arr2.includes(item));
}
const isDuplicate = (str) =>{
return new Set(str.split("")).size === str.length;
}
You could use reduce:
const arr = ["q", "w", "w", "e", "i", "u", "r"]
arr.reduce((acc, cur) => {
if(acc[cur]) {
acc.duplicates.push(cur)
} else {
acc[cur] = true //anything could go here
}
}, { duplicates: [] })
Result would look like this:
{ ...Non Duplicate Values, duplicates: ["w"] }
That way you can do whatever you want with the duplicate values!
I'm using regex to test certain elements in an array of arrays. If an inner array doesn't follow the desired format, I'd like to remove it from the main/outer array. The regex I'm using is working correctly. I am not sure why it isn't removing - can anyone advise or offer any edits to resolve this problem?
for (var i = arr.length-1; i>0; i--) {
var a = /^\w+$/;
var b = /^\w+$/;
var c = /^\w+$/;
var first = a.test(arr[i][0]);
var second = b.test(arr[i][1]);
var third = c.test(arr[i][2]);
if ((!first) || (!second) || (!third)){
arr.splice(i,1);
}
When you cast splice method on an array, its length is updated immediately. Thus, in future iterations, you will probably jump over some of its members.
For example:
var arr = ['a','b','c','d','e','f','g']
for(var i = 0; i < arr.length; i++) {
console.log(i, arr)
if(i%2 === 0) {
arr.splice(i, 1) // remove elements with even index
}
}
console.log(arr)
It will output:
0 ["a", "b", "c", "d", "e", "f", "g"]
1 ["b", "c", "d", "e", "f", "g"]
2 ["b", "c", "d", "e", "f", "g"]
3 ["b", "c", "e", "f", "g"]
4 ["b", "c", "e", "f", "g"]
["b", "c", "e", "f"]
My suggestion is, do not modify the array itself if you still have to iterate through it. Use another variable to save it.
var arr = ['a','b','c','d','e','f','g']
var another = []
for(var i = 0; i < arr.length; i++) {
if(i%2) {
another.push(arr[i]) // store elements with odd index
}
}
console.log(another) // ["b", "d", "f"]
Or you could go with Array.prototype.filter, which is much simpler:
arr.filter(function(el, i) {
return i%2 // store elements with odd index
})
It also outputs:
["b", "d", "f"]
Your code seems to work to me. The code in your post was missing a } to close the for statement but that should have caused the script to fail to parse and not even run at all.
I do agree with Leo that it would probably be cleaner to rewrite it using Array.prototype.filter though.
The code in your question would look something like this as a filter:
arr = arr.filter(function (row) {
return /^\w+$/.test(row[0]) && /^\w+$/.test(row[1]) && /^\w+$/.test(row[2]);
});
jsFiddle
I'm assuming it is 3 different regular expressions in your actual code, if they are all identical in your code you can save a little overhead by defining the RegExp literal once:
arr = arr.filter(function (row) {
var rxIsWord = /^\w+$/;
return rxIsWord.test(row[0]) && rxIsWord.test(row[1]) && rxIsWord.test(row[2]);
});