new to javascript. i have these two arrays
var array1 = [['1'],['2']];
var array2 = [['2'],['3'],['4']];
how can i find the matching values?
tried below but returns empty array probably because it's for normal array structure ['', '', '']
var matchingValue = array1.filter(value => array2.includes(value));
Logger.log(matchingValue);
Matching value should be ['2']
You can simply use .flat() to flatten the arrays so you only deal with the values like so :-
var array1 = [['1'],['2']];
var array2 = [['2'],['3'],['4']];
var matchingValue = array1.flat().filter((value) => array2.flat().includes(value) )
console.log(matchingValue);
First, let's have a function that tells if two arrays are equal:
let equal = (a, b) => a.length === b.length && a.every((_, i) => a[i] === b[i])
Then, use this function to find an intersection of two arrays:
var array1 = [['1'],['2']];
var array2 = [['2'],['3'],['4']];
let equal = (a, b) => a.length === b.length && a.every((_, i) => a[i] === b[i])
result = array1.filter(x => array2.some(y => equal(x, y)))
console.log(result)
In a more generic way, you can write intersectBy that would compute an intersection using a predicate callback:
let intersectBy = (a, b, predicate) =>
a.filter(x => b.some(y => predicate(x, y)))
Array.includes compares by identity, so it works with primitives and not with Array and Objects.
This is a solution that compares the first element of the internal arrays:
var matchingValue = array1.filter(value1 => {
return array2.map(value2 => value2[0]).includes(value1[0]);
});
Array.map is used to convert an Array of Arrays in Array of strings, then Array.includes is used to match the first element of first Array.
This works only with the current structure (arrays of one element arrays).
const array1 = [['1'],['2']];
const array2 = [['2'],['3'],['4']];
const array1Flat = [].concat(...array1);
const array2Flat = [].concat(...array2);
const matchingValue = array1Flat.filter((value) => array2Flat.includes(value));
console.log(matchingValue);
You don't need to use .flat() you can simply use concat and spread to flatten the array.
Related
I have two Arrays which look like this:
array1: [["abc","def","ghi"],["jkl","mno","pqr"]],
array2: [[1,2,3,4,5],[6,7,8,9,10]]
I want to operate a Flattening operation which gives me result like this: Flatten(array1,array2):
result: [["abc","def","ghi",1,2,3,4,5],["jkl","mno","pqr",6,7,8,9,10]]
Any suggestions on the same?
Edit 1: Both the Arrays always have the same length.
You can use map() on one of them and concat() it with corresponding element of other array
Note: I am considering length of both the arrays will be equal
const arr1 = [["abc","def","ghi"],["jkl","mno","pqr"]];
const arr2 = [[1,2,3,4,5],[6,7,8,9,10]];
const flattern = (a1, a2) => a1.map((x, i) => x.concat(a2[i]))
console.log(flattern(arr1, arr2))
If lengths of arrays are not same then you will have to first find the larger array and then map over it.
const arr1 = [["abc","def","ghi"],["jkl","mno","pqr"], ['a','b','c']];
const arr2 = [[1,2,3,4,5],[6,7,8,9,10]];
const flattern = (a1, a2) =>{
if(a1.length === a2.length){
return a1.map((x, i) => x.concat(a2[i]))
}
else if(a1.length > a2.length){
return a1.map((x, i) => x.concat(a2[i] || []))
}
else{
return a2.map((x, i) => x.concat(a1[i] || []))
}
}
console.log(flattern(arr1, arr2))
Since the length of the array is same, you could use map() over one array and concat the other.
const array1 = [["abc","def","ghi"],["jkl","mno","pqr"]];
const array2 = [[1,2,3,4,5],[6,7,8,9,10]];
let result = array1.map((a, i) => a.concat(array2[i]));
console.log(result);
You can use [...].flat(), see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat
var arr = [1,2,3,4]
arr.map((x,i) => arr[i+1] - x)
// 1,1,1,NaN
Is there a way you can use the index in an Array.map or Array.filter method to compare value with-out comparing the final index to avoid the outcome of NaN?
You can use Array#slice to remove the last element before applying map.
var arr = [1,2,3,4]
console.log(arr.slice(0,-1).map((x,i) => arr[i+1] - x));
The shortest way you could do this would be
var mapped = arr.map((x,i) => arr[i+1] - x).filter(x => x);
Which is saying filter all the values where x is True
But I don't think you can do this with only map. I think map always returns an array of equal length.
You use reduce to achieve this though.
var arr = [1,2,3,4]
var reduced = arr.reduce((ids,x,i) => {
if (i < arr.length-1 ){
ids.push(arr[i+1] - x)
}
return ids
}, []);
console.log(reduced)
Outputs
[ 1, 1, 1 ]
Yes, you can. Just use Arra.filter() and return only the value that has a primitive value:
var arr = [1,2,3,4];
var newArr = arr.map((x,i) => arr[++i] - x)
.filter(val => val);
console.log(newArr);
This function current takes in an array, and outputs it a character with its count if the element's length is greater than one
Is there a way I can do this same thing, perhaps with a different javascript array method without having to use a new array or a result variable?
const a = ['aaa', 'z', 'eeeee'];
const compressCharacters = arr => {
let newArray = [];
let result = arr.forEach(e => e.length > 1 ? newArray.push(`${e[0]}${e.length}`) : newArray.push(e))
return newArray.join("");
}
console.log(compressCharacters(a));
You can just use map() instead of forEach() and return the values you want. There's no need for the extra array. It's often the case than forEach + push() == map()
const a = ['aaa', 'z', 'eeeee'];
const compressCharacters = arr => {
return arr.map(e => e.length > 1
? `${e[0]}${e.length}`
: e)
.join("");
}
console.log(compressCharacters(a));
You can construct and immediately return a mapped array, that's joined by the empty string:
const a = ['aaa', 'z', 'eeeee'];
const compressCharacters = arr => (
arr.map(str => str[0] + (str.length > 1 ? str.length : ''))
.join('')
)
console.log(compressCharacters(a));
When you're trying to construct a new array by transforming all elements from some other array, .map is the appropriate method to use. forEach should be reserved for generic iteration with side effects, when you aren't trying to construct a new object. (when you are trying to construct a new object, but it's not an array, or the new array isn't one-to-one with the old array, usually you can use .reduce)
This is an alternative using the function reduce to build the desired output.
const a = ['aaa', 'z', 'eeeee'],
result = a.reduce((a, [m], i, arr) => {
let {length} = arr[i];
return a + m + (length <= 1 ? "" : length);
}, "");
console.log(result);
I came across with a weird requirement and I am struggling for last few hours to complete it. Below is my Array of string(just an example, the actual array contains around 2500 records):
var testArray = [
"130,839.9,855,837.3,848.65,3980489",
"129,875,875,828.1,833.25,6926078",
"138,891.3,893.3,865.2,868.75,5035618"
]
We have 3 element here of which each element is comma separated(each element have 6 item). i.e:
testArray[0] = "130,839.9,855,837.3,848.65,3980489"
My problem is, I wanted to sort testArray based on the first item of each element and convert it to array of array having all value into float, so the output would be:
[
[129, 875, 875, 828.1, 833.25, 6926078],
[130, 839.9, 855, 837.3, 848.65, 3980489],
[138, 891.3, 893.3, 865.2, 868.75, 5035618]
]
I am able to sort individual item but not the entire array as a whole, and I have tried using split and then sort with no luck.
Can someone help me out with this and please let me know if I am not clear.
Convert the array using Array#map within an Array#map, then use Array#sort on the converted array according to the [0] indices (a[0] - b[0]):
In ES5
var testArray = [
"130,839.9,855,837.3,848.65,3980489",
"129,875,875,828.1,833.25,6926078",
"138,891.3,893.3,865.2,868.75,5035618"
]
var converted = testArray.map(function (item) {
return item.split(',').map(function (num) {
return parseFloat(num);
});
})
console.log(converted)
var sorted = converted.sort(function (a, b) { return a[0] - b[0] })
console.log(sorted)
In ES6
const testArray = [
"130,839.9,855,837.3,848.65,3980489",
"129,875,875,828.1,833.25,6926078",
"138,891.3,893.3,865.2,868.75,5035618"
]
const converted = testArray.map(
item => item.split(',').map(
num => parseFloat(num)
)
)
console.log(converted)
const sorted = converted.sort((a, b) => a[0] - b[0])
console.log(sorted)
In ES6 (condensed)
const testArray = [
"130,839.9,855,837.3,848.65,3980489",
"129,875,875,828.1,833.25,6926078",
"138,891.3,893.3,865.2,868.75,5035618"
]
const convertedAndSorted = testArray
.map(n => n.split(',')
.map(num => parseFloat(num)))
.sort((a, b) => a[0] - b[0])
console.log(convertedAndSorted)
Just map the splitted and to number formatted values and sort by the first item.
var data = ["130,839.9,855,837.3,848.65,3980489", "129,875,875,828.1,833.25,6926078", "138,891.3,893.3,865.2,868.75,5035618"],
result = data
.map(s => s.split(',').map(Number))
.sort((a, b) => a[0] - b[0]);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
var testArray = ["130,839.9,855,837.3,848.65,3980489","129,875,875,828.1,833.25,6926078","138,891.3,893.3,865.2,868.75,5035618"];
const output = [];
for (let i = 0; i < testArray.length; i++) {
var numbers = testArray[i].split(',');
for (let j = 0; j < numbers.length; j++) {
numbers[j] = +numbers[j];
}
output[i] = numbers;
}
output.sort(function(x, y) {
return x[0] - y[0];
});
or shorter
output = testArray.map(s => s.split(',')).map(e => e.map(n => +n)).sort((x, y) => x[0] - y[0]);
First convert each of the Strings to an array of floats values using Array.map() and parseFloat().
After that you can simply sort the array of arrays using Arrays.sort()
Try the following :
var arr = ["130,839.9,855,837.3,848.65,3980489","129,875,875,828.1,833.25,6926078","138,891.3,893.3,865.2,868.75,5035618"];
var result = arr.map((a)=> a.split(",").map((b)=>parseFloat(b))).sort((a,b)=> a[0] -b[0]);
console.log(result);
I have to sort a string array based on the number.
Example
["1.READ","10.CREATE","3.sfg","2.dfd","12.dqwe"];
Desired Result
["1.READ","2.dfd","3.sfg","10.CREATE","12.dqwe"];
My Code
var arr = ["1.READ","10.CREATE","3.sfg","2.dfd","12.dqwe"];
var arr2 = arr.map( a => a.split('.').map( n => +n+100000 ).join('.') ).sort().map( a => a.split('.').map( n => +n-100000 ).join('.') );
console.log(arr);
console.log(arr2);
You can just split and convert the first element to Number
var arr = ["1.READ", "10.CREATE", "3.sfg", "2.dfd", "12.dqwe"];
var arr2 = arr.sort((a, b) => {
return Number(a.split(".")[0]) - Number(b.split(".")[0]);
});
console.log(arr2);
The code above will also sort the first variable. If you you only want arr2 to be sorted, you can:
var arr = ["1.READ", "10.CREATE", "3.sfg", "2.dfd", "12.dqwe"];
var arr2 = [...arr]; //Spread the array so that it will not affect the original
arr2.sort((a, b) => {
return Number(a.split(".")[0]) - Number(b.split(".")[0]);
});
console.log(arr);
console.log(arr2);
You could split and take only the first part. Then take the delta for sorting.
var array = ["1.READ", "10.CREATE", "3.sfg", "2.dfd", "12.dqwe"];
array.sort((a, b) => a.split(".")[0] - b.split(".")[0]);
console.log(array);
Here it is:
var arr = ["1.READ","10.CREATE","3.sfg","2.dfd","12.dqwe"];
arr.sort(function(a, b) {
return a.split('.')[0] - b.split('.')[0];
});
console.log(arr)
// ["1.READ", "2.dfd", "3.sfg", "10.CREATE", "12.dqwe"]
This answer base on built in array sort function, with customizable compare logic.
Check this out for more detail: Javascript Array Sort
Cheers,