I have an array:
["1", "2","3","4","5"]
that I would like to change to:
[["1, 0 ,0 ,0"], ["2, 0, 0, 0"],["3,0,0,0"],["4,0,0,0"],["5,0,0,0"]]
I've tried to achieve this with the following code:
var arr1 = ["1", "2","3","4","5"];
var arr2 = [,"0", "0","0"];
for(var z=0; z<arr1.length; z++)
{
arr1[z] = arr1[z].concat(arr2);
console.log(arr1)
}
However, this doesn't achieve what I want and places commas between each item, which I think is because it is not a string? I've tried using .join too but I couldn't get that to work either.
Could someone point me in the right direction for this please? Thanks.
You first need to convert each element to array and then append the second array to the newly converted array element. The following code snippet would make it clear -
var arr1 = ["1", "2", "3", "4", "5"];
var arr2 = [ "0", "0", "0"];
for (var z = 0; z < arr1.length; z++) {
// First convert the element into a list
arr1[z] = [arr1[z]];
// Then append the second array to it
arr1[z] = arr1[z].concat(arr2);
// Another way -
//arr1[z].push(...arr2);
}
// Final array -
console.log(arr1);
Using Map() :
Another way to do it would be using map() as below -
var arr1 = ["1", "2", "3", "4", "5"];
var arr2 = [ "0", "0", "0"];
arr1 = arr1.map(el=>[el,...arr2]);
console.log(arr1);
Using ForEach()
You could also do it using forEach() method -
var arr1 = ["1", "2", "3", "4", "5"];
var arr2 = [ "0", "0", "0"];
// this will note mutate original arr1 and store result in res
let res = [];
// ... is the spread operator which will allows iterable objects to be expanded in place
arr1.forEach(el=>res.push([el,...arr2]));
// final result
console.log(res);
There's probably numerous other ways as well... These were just few I have listed. You could even do it using naive nested loops method if you don't know anything about map(), forEach(), or concat() / push() methods.
Hope this helps !
Please try the following example
const array = ["1", "2", "3", "4", "5"];
const output = array.map((entry) => [`${entry}, 0, 0, 0`]);
console.log(output);
See
Array.prototype.map()
Template literals (Template strings)
if it's set in stone, you can do
let arr = []
var arr1 = ["1", "2","3","4","5"];
var arr2 = ["0", "0","0"];
arr1.forEach(el=>arr.push([el, ...arr2]));
console.log(arr)
Use map to go through each of your element and append the array with zeros, transform it to a string and wrap in an array again which will hold one value
const a = ["1", "2", "3", "4", "5"]
const arr = [0, 0, 0, 0];
const res = a.map(x => [
[x, ...arr].join()
])
console.log(res)
Related
Im trying to split all the numbers in a array:
var array_code = [116,101,120,116];
So i want the result to look like this: [1,1,6,1,0,1,1,2,0,1,1,6]
the code im working on right now looks like this:
var array_gesplit = new Array;
for(var i=0; i< array_code.length; i++){
console.log(array_code[i])
while (array_code[i]) {
array_gesplit.push(array_code[i] % 10 );
array_code[i] = Math.floor(array_code[i]/10);
}
}
The result im getting from this is:
[
6, 1, 1, 1,
0, 1, 0, 2,
1, 6, 1, 1
]
Who can help me ?
You can use Array.from() method for this:
var array_code = [116,101,120,116];
var result = Array.from(array_code.join(''), Number)
console.log(result)
Explanation:
array_code.join('') creates a string like "116101120116"
Array.from('116101120116') on this string results in new Array of strings like:
["1", "1", "6", "1", "0", "1", "1", "2", "0", "1", "1", "6"]
We can also use Array.from() with map function, so that we can convert all these string values to Number in one line like:
Array.from(array_code.join(''), x => Number(x))
Or, just Array.from(array_code.join(''), Number)
The above logic result is the required output.
You can use flatMap() and convert number to string and use built-in split() method.
var array_code = [116,101,120,116];
const res = array_code.flatMap(x => x.toString().split('').map(Number));
console.log(res)
You could take strings and map numbers.
var code = [116, 101, 120, 116],
result = code.flatMap(v => Array.from(v.toString(), Number));
console.log(result);
Here's a hack by using some details of the JavaScript language:
var array_code = [116, 101, 120, 116];
var array_string = JSON.stringify(array_code);
var array_parts = [].slice.call(array_string);
var parts = array_parts.slice(1, -1); // get rid of the square brackets
console.log(parts);
I'm looking for an efficient solution to sort an array depending of how many times an element appears
For example :
let values = ["10", "4", "4", "4", "7", "7"]
I think the best output would be something like [{number, frequency}, ...], which, in the example would look like this :
[{4, 3}, {7, 2}, {10, 1}]
I've seen a lot of ways to do it, but every solution just sort the array depending of the frequency, without any access on how many times the element appears.
At the moment I only have this code that I got from another StackOverflow topic (can't remember which one sorry)
var map = values.reduce(function(p, c) {
p[c] = (p[c] || 0) + 1;
return p;
}, {});
var newTypesArray = Object.keys(map).sort(function(a, b) {
return map[a] < map[b];
});
console.log(newTypesArray);
It's doing a great job at sorting depending on the frequency, but I can't access how many times an element is repeated. And I have no idea how to do it...
Any thoughts?
const arr = [1, 1, 1, 2, 2, 3];
// use reduce for that.
const result = arr.reduce((result, item) => {
const count = result[item];
if (count === undefined) {
result[item] = 1;
} else {
result[item] += 1;
}
return result;
}, {});
// You'll get the result similar to this: {[item]: [count]}
// And then you can transform it into entries array:
const entries = Object.entries(result);
// entries are [[item, count], ...];
// And then sort
const sorted = entries.sort((entryA, entryB) => entryA[1] - entryB[1]);
// You'll have ascending sorted array by count.
console.log(sorted);
Something like this might do the trick:
const data = ["10", "7", "5", "4", "4", "7", "7", "4", "5", "4"];
const result = data.reduce((r, c) => (r[c] = (r[c] || 0) + 1, r), {});
var keys=Object.keys(result).sort((a,b)=>result[b]-result[a]); // sorted keys
console.log(keys.map(k=>k+':'+result[k])); // output, ordered by keys
It is up to you how you want to return the results. result contains the count and keys the actual values.
You can use Object.entries() over the object you got from reduce now sorting the array of key-value pairs and finally mapping to the array of {number, frequency}:
let values = ["10", "4", "4", "4", "7", "7"]
var map = Object.entries(values.reduce(function(p, c) {
p[c] = (p[c] || 0) + 1;
return p;
}, {}))
.sort((a, b) => a[1] < b[1])
.map((a) => ({[a[0]]:a[1]}));
console.log(map);
I think the best output would be something like [{number, frequency}, ...]
Actually these are not valid JavaScript objects inside your output array, if you want to show them as pairs you can use an array of arrays instead of this, the result will be like this:
[[number, frequency], ...]
In your code you were almost there, but you just need to map the result of your first reduce call to get the desired pair:
let values = ["10", "4", "4", "4", "7", "7"];
var map = values.reduce(function(p, c) {
p[c] = (p[c] || 0) + 1;
return p;
}, {});
var newTypesArray = Object.keys(map).map(function(k) {
return [+k, map[k]];
}).sort((a,b) => b[1] - a[1]);
console.log(newTypesArray);
I have a problem where i must take an array of strings(some numbers and some letters)and remove the Zeros, move them to the end, and return the array. The final result needs all of the numbers to be integers in the string.
I have tried mapping the array and parsing the integers. This works unless the array passed in has letters. then all the letters are relaced with NaN. I cant seem to set up a conditional that will only operate on the integers.
var final = ["a","b","c","d","1","1","3","1","9","9",0,0,0,0,0,0,0,0,0,0];
but it should be
var final = ["a","b","c","d",1,1,3,1,9,9,0,0,0,0,0,0,0,0,0,0]
I need to parse the integers but cant get map to do it without the problem i described earlier. I also tried using if statements too, with no help.
You could convert all numbers or try to convert and take the value, if the conversion is falsy.
var final = ["a", "b", "c", "d", "1", "1", "3", "1", "9", "9", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
console.log(final.map(v => +v || v));
Zero safe approach.
var final = ["a", "b", "c", "d", "1", "1", "3", "1", "9", "9", "0", 0, 0, 0, 0, 0, 0, 0, 0, 0];
console.log(final.map(v => isNaN(v) ? v : +v));
You can try with isNaN() and Array.prototype.map() along with Conditional (ternary) operator:
var final = ["a","b","c","d","1","1","3","1","9","9",0,0,0,0,0,0,0,0,0,0];
final = final.map(i => isNaN(i) ? i : Number(i));
console.log(final);
You want to parse the number but return the original element if it's NaN using a conditional:
var final = array.map((x) => {
var n = parseInt(x, 10);
return !isNaN(n) ? x : n;
})
You could use this:
var input = ["0", "a", "0", "b", "0", "0", "c", "d", "0", 0, "0", "1", "0", "1","3","0", "1","9","9", "0"];
var final = [...input.filter(s => s != 0),
...input.filter(s => s == 0)
].map(s => isNaN(s) ? s : +s);
console.log(final);
Using map() and validating on isNaN().
["a","b","c","d","1","1","3","1","9","9",0,0,0,0,0,0,0,0,0,0]
.map(x => !isNaN(x) ? Number(x) : x)
can you explain the logic how to convert this 2d array to array and in array has objects, here is the input :
const arr = [
["Tony", "a", "b"],
["Sara", "c", "z"]
];
how to convert them to be:
obj = [
{
name:"Tony",
first:"a",
second:"b"
},
{
name:"Sara",
first:"c",
second:"z"
}
]
should we create 2 objects temporary and are ? to put them in the array,
and how about looping? can we just use one-time looping?
and how if that 2d array length is not same with ther 2d on the first or the second,
i do love to know the method, with explaning if you dont mind,
and i do like you all dont use ES6 for this :), so i know the logic
Use Array.map(). In the map's callback, extract the values to variables, using array destructuring, than create the object with shorthand property names:
const arr = [["Tony", "a", "b"], ["Sara", "c", "z"]];
const result = arr.map(([name, first, second]) => ({
name,
first,
second
}));
console.log(result);
And if you don't want to use Array.map(), you can build one using a for...of loop:
const map = (arr, cb) => {
const r = [];
for(const item of arr) {
r.push(cb(item));
}
return r;
};
const arr = [["Tony", "a", "b"], ["Sara", "c", "z"]];
const result = map(arr, ([name, first, second]) => ({
name,
first,
second
}));
console.log(result);
You can use .map() with some array destructuring:
const arr = [
["Tony", "a", "b"],
["Sara", "c", "z"]
];
const result = arr.map(([name, first, second]) => ({name, first, second}));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Alternatively, you can use a simple for loop:
const arr = [
["Tony", "a", "b"],
["Sara", "c", "z"]
];
const result = [];
for(var i = 0; i < arr.length; i++) {
result.push({
name: arr[i][0],
first: arr[i][1],
second: arr[i][2]
});
}
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
var arr = [["Tony", "a", "b"], ["Sara", "c", "z"]];
function parseData(input){
var output = [];
for(var i = 0; i< input.length ; i++){
output.push({name:input[i][0],first:input[i][1],second:input[i][2]})
}
return output;
}
console.log(parseData(arr));
EDIT - Explanation
As the input is structured as 2D array with inner array is of fixed length of 3 and outer is of non-negative ( >= 0 ). Iterate over the outer array using for loop and inner array using the index number and store the result in output array.
JsFiddle demo - https://jsfiddle.net/53umf8rv/
Without Map:
const arr = [
["Tony", "a", "b"],
["Sara", "c", "z"]
];
obj=[];
for(innerArr of arr)
{
obj.push({"name":innerArr[0],"first":innerArr[1],"second":innerArr[2]});
}
console.log(obj);
Without using higher order functions you can achieve this using a for of loop:
const arr = [
["Tony", "a", "b"],
["Sara", "c", "z"]
];
let obj_arr = [];
for(inner_arr of arr) {
obj_arr = [...obj_arr, {name: inner_arr[0], first: inner_arr[1], second: inner_arr[2]}];
}
console.log(obj_arr);
You could use an outer for ... of statement, which iterates the items of the array and iterate the inner array by using a classic for statement with an index variable, which is used to get the corresponding key value as well.
For each inner iteration take a new property for the temporary object and assign a value. At the end of the inner iteration push the temporary object to the result set.
function convert(array, keys) {
var result = [],
items,
i,
temp;
for (items of array) {
temp = {};
for (i = 0; i < items.length; i++) {
temp[keys[i]] = items[i];
}
result.push(temp);
}
return result;
}
console.log(convert([["Tony", "a", "b"], ["Sara", "c", "z"]], ["name", "first", "second"]));
While trying to get all permutations using Heap's algorithm, I met trouble storing the results in array.
The result generated is (from console.log(arr);)
["1", "2", "3"]
["2", "1", "3"]
["3", "1", "2"]
["1", "3", "2"]
["2", "3", "1"]
["3", "2", "1"]
but only the last value is stored in the arr, and the array stored somehow is this (from console.log(JSON.stringify(allPermutations)); )
["3", "2", "1"]
["3", "2", "1"]
["3", "2", "1"]
["3", "2", "1"]
["3", "2", "1"]
["3", "2", "1"]
var allPermutations = [];
function swap(arr,index1,index2){
var dummy = arr[index1];
arr[index1] = arr[index2];
arr[index2] = dummy;
return arr;
}
function generate(n,arr){
if(n==1){
console.log(arr);
//result:
//["1", "2", "3"]
//["2", "1", "3"]
//["3", "1", "2"]
//["1", "3", "2"]
//["2", "3", "1"]
//["3", "2", "1"]
allPermutations.push(arr);
}else{
for(var i=0;i<n-1;i++){
generate(n-1,arr);
if( n%2 ==0){
arr = swap(arr,i,n-1);
}else{
arr = swap(arr,0,n-1);
}
}
generate(n - 1, arr);
}
}
generate(3,['1','2','3']);
console.log(JSON.stringify(allPermutations));
/*result:
["3","2","1"]
["3","2","1"]
["3","2","1"]
["3","2","1"]
["3","2","1"]
["3","2","1"]*/
What's wrong with this? Would love to understand. Thanks
Replace allPermutations.push(arr) with allPermutations.push(arr.slice()).
The problem is, you keep pushing the same array, then changing that array. When you push an array, you don't push a copy of it: you push a reference. There is only one array, and six references to it; when you read them out, they all read the same, because they are all the same array.
.slice() will give you a new array with the same elements; this way, you get six new arrays into your result, instead of six mentions of the same array.
From one of my earlier answers that is almost-but-not-quite a duplicate, a metaphor I like for this:
As a metaphor, imagine a theatre director in casting. He turns to an actor, says "You... you'll be Romeo.". Then he looks at the same actor, says "You... you'll be Mercutio. Here, Mercutio, take this sword. Romeo... who told you to get a sword?!?" completely failing to realise that, if Romeo and Mercutio are the same person, if one of them picks up a sword, the other does it too.
That's because arrays are objects, and objects are passed by value, but that value is a reference.
Then, your code keeps pushing the same arr reference to allPermutations. But the values in that reference are modified later.
Instead, you should push a copy of the array. You can copy it with .slice().
var allPermutations = [];
function swap(arr, index1, index2) {
var dummy = arr[index1];
arr[index1] = arr[index2];
arr[index2] = dummy;
return arr;
}
function generate(n, arr) {
if (n == 1) {
allPermutations.push(arr.slice());
} else {
for (var i = 0; i < n - 1; i++) {
generate(n - 1, arr);
if (n % 2 == 0) {
arr = swap(arr, i, n - 1);
} else {
arr = swap(arr, 0, n - 1);
}
}
generate(n - 1, arr);
}
}
generate(3, ['1', '2', '3']);
document.write(JSON.stringify(allPermutations));