For example i have a array like that
var myArray = [
[1,2,3],
[4,5,6],
[7,8,9,10],
[[11,12],[13,14,15]]];
for (var i = 0;i < myArray.length;i++){
for(var j = 0 ;j< myArray[i].length;j++){
for(var k = 0;k< myArray[i][j].length;k++){
console.log(myArray[i],[j][k]);
}
}
}
But output is only 11,12,13,14,15.
And i wanna print all the values
Could some one help to fix
Thank you in advance
Use e.g. Array.prototype.flat(), .flat(2) flattens to the level of 2 arrays deep.
var myArray = [
[1,2,3],
[4,5,6],
[7,8,9,10],
[[11,12],[13,14,15]]];
console.log(myArray.flat(2));
You can use recursive function
first pass it the whole array then loop it and check if the element you are accessing is array or digit
if its array call the same function again and only pass it this element
otherwise if its digit just print it
This works even when you dont know how many nested arrays you have otherwise use MWO answer
var myArray = [
[1,2,3],
[4,5,6],
[7,8,9,10],
[[11,12],[13,14,15]]];
function printArray(arr){
for(var i = 0; i < arr.length; i++){
if(Array.isArray(arr[i])){
printArray(arr[i]);
}else{
console.log(arr[i]);
}
}
}
printArray(myArray);
This fucntion works for any depth of multi dimensional array. Using Recursion
var myArray = [1,2,33,44, [1,2,3], [[11,12],[13,14,15]]];
var myArray1 = [1,2,33,44, [[11,12],[13,14,15]]];
var deepFlattenArray = function (array){
var result = [];
array.forEach(function (element) {
if (Array.isArray(element)) {
result = result.concat(deepFlattenArray(element));
} else {
result.push(element);
}
});
return result;
};
console.log(deepFlattenArray(myArray));
// output = [ 1, 2, 33, 44, 1, 2, 3, 11, 12, 13, 14, 15]
console.log(deepFlattenArray(myArray1));
// output = [1, 2, 33, 44, 11, 12, 13, 14, 15 ]
Related
I need to remove similar duplicates as well as real duplicates from 2D array in JavaScript.
let a = [
[5, 6],
[1,1],
[6,5],
[1,1],
[3,2],
[2,3]
]
function makeUnique(arr) {
var uniques = [];
var itemsFound = {};
for(var i = 0, l = arr.length; i < l; i++) {
var stringified = JSON.stringify(arr[i]);
if(itemsFound[stringified]) continue;
uniques.push(arr[i]);
itemsFound[stringified] = true;
}
return uniques;
}
a=makeUnique(a)
console.log(a);
I have got this output:
[ [ 5, 6 ], [ 1, 1 ], [ 6, 5 ], [ 3, 2 ], [ 2, 3 ] ]
Correct should be:
[ [ 5, 6 ], [ 1, 1 ], [ 2, 3 ] ]
My code removes correctly duplicates, but I need to remove similar duplicates also.
For example if I have [3,2] and [2,3] I should remove [3,2] (the one which has bigger starting index value.)
Could you help me to fix this?
Here is an example of how you can do it:
function makeUnique(arr) {
var uniques = [];
var itemsFound = {};
arr.sort((a, b) => a[0] + a[1] - (b[0] + b[1]))
for (var i = 0, l = arr.length; i < l; i++) {
if (!itemsFound[arr[i]] && !itemsFound[[arr[i][1], arr[i][1]]]) {
uniques.push(arr[i]);
itemsFound[arr[i]] = true;
itemsFound[[arr[i][1], arr[i][0]]] = true;
}
}
return uniques;
}
I hope it helps.
There are two parts
similar should be considered
among similar, one with smaller first key should stay
1. Similar should be considered
Here you can just make the key for hashmap in such a way that similar items produce same key.
One way to do that is sort the items in the tuple and then form the key, as there are two items only, first one will be min and second one will be max
let a = [
[5, 6],
[1,1],
[6,5],
[1,1],
[3,2],
[2,3]
]
function makeUnique(arr) {
var uniques = [];
var itemsFound = {};
for(var i = 0, l = arr.length; i < l; i++) {
let [a,b] = arr[i];
const hashKey = [ Math.min(a,b), Math.max(a,b)];
var stringified = JSON.stringify(hashKey);
if(itemsFound[stringified]) continue;
uniques.push(arr[i]);
itemsFound[stringified] = true;
}
return uniques;
}
let ans1=makeUnique(a)
console.log(ans1);
2. Among similar, the one with smaller first key should stay
Now you can remember in the hashmap what the value for a key was and keep updating it based on the correct candidate
let a = [
[5, 6],
[1,1],
[6,5],
[1,1],
[3,2],
[2,3]
]
function makeUniqueSmallerFirst(arr) {
var items = {};
for(var i = 0, l = arr.length; i < l; i++) {
let [a,b] = arr[i];
const hashKey = [ Math.min(a,b), Math.max(a,b)];
var stringified = JSON.stringify(hashKey);
if (stringified in items) {
let previous = items[stringified];
if (previous[0] > arr[i][0]) {
items[stringified] = arr[i];
}
} else {
items[stringified] = arr[i] // I am just storing the array because if I see a similar item next time, I can compare if that has first item smaller or not
}
}
return Object.values(items); // this doesn't guarantee output order though
// if you want order as well . you can iterate over input array once more and arrange the items in the preferred order.
}
let ans2=makeUniqueSmallerFirst(a)
console.log(ans2);
UPDATED (More simple and faster example for ES5+):
function makeUnique(arr) {
return new Set(a.map(
arr => JSON.stringify(arr.sort((a, b) => a - b)))
)
}
const m = makeUnique(a)
console.log(m) //
OLD:
This is an example of code that makes a two-dimensional array with arrays of any length unique.
let a = [
[5, 6],
[1, 1],
[6, 5],
[1, 5],
[3, 2],
[2, 3],
[6, 5, 3],
[3, 5, 6]
]
function isUnique(uniqueArray, checkedArray) {
let checked = [...checkedArray];
let unique = [...uniqueArray];
let uniqueValue = 0;
unique.forEach(value => {
if (checked.includes(value)) {
checked.splice(checked.indexOf(value), 1)
} else uniqueValue++;
})
return uniqueValue > 0;
}
function makeUnique(array2d) {
let unique = [array2d[0]]
array2d.forEach(checkedArray => {
if (unique.some(uniqueArray => {
if (checkedArray.length !== uniqueArray.length) return false;
return !isUnique(uniqueArray, checkedArray)
}
)) return 0;
else unique.push(checkedArray)
})
return unique
}
console.log(makeUnique(a)) // [ [ 5, 6 ], [ 1, 1 ], [ 1, 5 ], [ 3, 2 ], [ 6, 5, 3 ] ]
isUnique() this function checks if the numbers in both arrays are unique, and if they are, it outputs true. We use the copy through spread operator, so that when you delete a number from an array, the array from outside is not affected.
makeUnique() function makes the array unique, in the following way:
It checks if our unique two-dimensional array has at least one array that is identical to checkedArray
The first check if the arrays are of different lengths - they are unique, skip and check for uniqueness, if !isUnique gives out true, then the array is skipped by return 0
I am trying to create an object from 2 arrays.
var arr1 = ["2000", "10003", "1234000", "44444444", "9999", "11", "11", "22", "123"];
var arr2 = [2, 4, 10, 32, 36, 2, 2, 4, 6];
I used a for loop to populate the object:
var obj= {};
for(var i = 0; i < arr1.length; i++) {
obj[arr1[i]] = arr2[i];
}
Result:
[object Object] {
10003: 4,
11: 2,
123: 6,
1234000: 10,
2000: 2,
22: 4,
44444444: 32,
9999: 36
}
It does create the object based on my 2 arrays, but omit 1 value that is a duplicate in the arrays. I don't want to exclude them. What could be the trick to include ALL the array element in my object? The result is not even in the same order as the original arrays...
Thank you!
populate the values into array if that could be a workaround for you..
var obj= [];
for(var i = 0; i < arr1.length; i++) {
var obj1 ={};
obj1[arr1[i]] = arr2[i];
obj.push(obj1);
}
I'm trying to return the largest number in every array to one array with sort() method. I think I did the whole code correctly except sorting:
function largestOfFour(arr) {
let result=[];
for(let i=0; i < arr.length; i++) {
for(let j=0; j < arr[i].length; j++) {
let segregatedArr = arr[0][j].sort((a,b)=>b-a);
}
result = segregatedArr[0][i][0];
}
return result;
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
And I'm getting an error:
TypeError: arr[0][j].sort is not a function
I was trying the slice method or mapping to an array with:
result = $.map(arr, function(value, index) { return [value]; });
result.sort().reverse();
But the error was still the same in both cases.
function maxArr(arr2D) {
let result = [];
for(let i = 0; i < arr2D.length; i++) {
result[i] = arr2D[i].sort((a, b) => b - a)[0];
}
return result;
}
You can use Math.max.apply to get the largest number:
function largestOfFour(array){
var result = [];
for(var i=0; i<array.length;++i){
result.push(Math.max.apply(Math, array[i]));
}
return result;
}
So, I think for a post like this, it would be helpful if you provide a sample of the input and the desired output.
Are you trying to take as input an array of arrays? And then output a single array, where each element has the largest element of the original arrays? The sample input I created was as follows:
var a1 = [1, 2, 3];
var a2 = [5, 19, 7];
var a3 = [199, 198, 104];
var arrs = [a1, a2, a3];
// run the function and view its output:
console.log(largestOfFour(arrs));
// outputs [ 3, 19, 199 ]
If that is what you were going for, then I think you have too many loops (an outer loop with an unneeded inner loop), so that line of code:
let segregatedArr = arr[0][j].sort((a,b)=>b-a);
is accessing a number rather than an array of numbers. I modified the function as follows:
function largestOfFour(arr) {
let result=[];
for(let i=0;i<arr.length;i++){
let segregatedArr=arr[i].sort((a,b)=> b-a);
result.push(segregatedArr[0])
}
return result;
}
So, I removed the inner loop (with the 'j' index), and then the main loop just sorts the i'th array of the input arrays . Is that what you were going for?
var array = [
[1, 2, 3, 4],
[10, 5, 3, 4],
[11, 20, 13, 14],
[1, 2, 3, 40]
];
function maxVal(arr) {
var max = arr[0];
arr.forEach(function(item) {
max = Math.max(item, max);
});
return max;
};
function largestOfFour(arr) {
return arr.map(function(innerArray) {
return maxVal(innerArray);
});
}
console.log(largestOfFour(array));
or if you really really want to use sort :-)
function maxVal(arr) {
arr.sort(function(a, b) {
if (a === b) {
return 0;
}
return a > b ? -1 : 1;
});
return arr[0];
};
function largestOfFour(arr) {
return arr.map(function(innerArray) {
return maxVal(innerArray);
});
}
console.log(largestOfFour(array));
i've been instructed to create a function that takes values from an array and squares each value, and logging the numbers to the console. i've attempted two methods, neither of which work so far:
first attempt:
var numbers = [2, 7, 13, 24];
function squareAll(numbers) {
var newArray = [];
for(i = 0; i < numbers.length; i++) {
numbers = newArray.push(Math.pow(numbers[i], 2))
return newArray;
}
console.log(squareAll(numbers));
}
second attempt:
var numbers = [2, 7, 9, 25];
var newArray = [];
var squareAll = function(numbers) {
for(var i = 0; i < numbers.length; i++){
newArray = [];
newArray.push(squareAll[i] * squareAll[i])
};
return newArray;
};
console.log(squareAll(newArray));
when i try both codes in the javascript console, both return undefined and won't give me a specific error so i'm unsure what's wrong here. any explanation would be appreciated!
In your first attempt you are assigning a push method into a variable, which is a bad practice. Secondly, you are returning the function just right after the first cycle of the loop, so you are stopping the loop before going through all the elements of the array.
And in the second attempt, you are basically clearing the array after each cycle of the loop, because of the newArray = []; inside the loop. So with every cycle, you are dropping an element inside the newArray and then you are telling the loop to clear the newArray. The loop will become infinite, because the length of the newArray will never reach the numbers.length.
var numbers = [2, 7, 13, 24];
var newArray = [];
console.log(numbers.map(v => Math.pow(v, 2)));
Or:
var numbers = [2, 7, 13, 24];
var newArray = [];
for (var i = 0; i < numbers.length; i++) {
newArray.push(Math.pow(numbers[i], 2));
}
console.log(newArray);
Why not just use map
var result = [1,2,3,4,5].map(function(val){
return Math.pow(val,2);
});
console.log(result); // [1, 4, 9, 16, 25]
Use array.map() to set a callback function to be executed for each element in the array:
var arr1 = [1,2,3,4];
function squareIt(arr) {
return arr.map(function (x) {
return Math.pow(x, 2);
});
}
alert(squareIt(arr1));
So I have a javascript variable that looks like this
D,CPU_Purchased_ghz,2015-03-19 00:00:00,10.00,2015-03-20 00:00:00,10.00
Is it possible to split into an array like this:
[
[D,CPU_Purchased_ghz],
[2015-03-19 00:00:00,10.00],
[2015-03-20 00:00:00,10.00]
]
ie. I want to be able to split it into blocks of 2
This little function will chunk an array into blocks of a specified size:
var chunk = function (chunkSize, array) {
var chunked = []
var from
for (var i = 0, range = array.length / chunkSize; i < range; i++) {
from = i * chunkSize
chunked.push(array.slice(from, from + chunkSize))
}
return chunked
}
// Usage:
chunk(3, [1, 2, 3, 4, 5])
// -> [[1, 2, 3], [4, 5]]
If the variable you're using is actually an array:
var arr1 = [ "D", "CPU_Purchased_ghz", "2015-03-19 00:00:00", 10.00, "2015-03-20 00:00:00", 10.00 ];
var arr2 = [];
for(var i=0, l=arr1.length; i<l; i++){
arr2.push( [arr1[i], arr1[++i]] );
}
console.log(arr2); // Outputs [ ["D","CPU_Purchased_ghz"], ["2015-03-19 00:00:00",10.00], ["2015-03-20 00:00:00",10.00] ]
JS Fiddle Demo
(See Edit for Array solution)
This can be done nicely with a regular expression
var arr = aString.match(/[^,]+,[^,]+/g);
with aString containing your string.
Returns:
[
"D,CPU_Purchased_ghz",
"2015-03-19 00:00:00,10.00",
"2015-03-20 00:00:00,10.00"
]
JSFiddle
EDIT: I've just been notified that the variable might be an array and not a string. If that is indeed the case, just join the array first:
var arr = aArray.join(',').match(/[^,]+,[^,]+/g);
JsFiddle for array