Insert value multiple times into array based on argument passed - javascript

I have a array like this:
var oldArr = [2,3,4,2,3,5,6,4,2,3,2];
var newArr = [];
I am passing a argument(number) to a function which should insert values from oldArr into newArr taking the argument as length for each element found in old array.
function getNumbers(num){
console.log('value passed is ', num);
for(var i=0; i<arr.length;i++){
newArr.push(arr[i]);
}
console.log('newArr', newArr);
}
getNumbers(2);
For example,
if I pass number 2 as in getNumbers(2);
new array output should be:
[2,2,3,3,4,4,5,5,6,6] //as the argument/length passed is 2.
if I pass number 3 as in getNumbers(3);
[2,2,2,3,3,3,4,4,4,5,5,5,6,6,6] //as the argument/length passed is 3.
How do I achieve this?

Try this
var oldArr = [2,3,4,2,3,5,6,4,2,3,2];
function getNumbers(arr, num){
return Array.from(new Set(arr))
.map((e) => new Array(num).fill().map(v => e))
.reduce((a, b) => a.concat(b),[]);
}
console.log(getNumbers(oldArr, 2));
console.log(getNumbers(oldArr, 3));
First of all, you need to get the unique values from the array. That's the Array.from(new Set(arr));.
Secondly, we can allocate new array for each number (to be able to nicely flatten it later). That's what new Array(num).fill().map(v => e)) does. Result of this will be like [[2,2],[3,3],[4,4]..] etc.
And lastly, flatten it all using Array.prototype.reduce.

var oldArr = [2,3,4,2,3,5,6,4,2,3,2];
var uniqueArr = oldArr.filter(function(elem, index, self) {
return index == self.indexOf(elem);
})
console.log(uniqueArr)
function getNumbers(num){
var newArr = [];
for(var i=0; i<uniqueArr.length;i++){
for(var j=0;j<num;j++)
newArr.push(uniqueArr[i]);
}
console.log('newArr', newArr);
}
getNumbers(2);
getNumbers(3);
Remove all your duplicates from your old array using Array#Filter , then loop through all element and store it in new array.

The following function should work
function duplicateN(oldArray, newArray, N) {
for (var i = 0; i < oldArray.length; i++) {
for (var j = 0; j < N; j++) {
newArray.push(oldArray[i]);
}
}
}
It simply iterates over each value in the original array and then inserts it N times.
I'm not sure the usage of this, but if newArray is always empty, something like this would be more maintainable
function duplicateN(inputArray, N) {
var duplicatedArray = [];
for (var i = 0; i < inputArray.length; i++) {
for (var j = 0; j < N; j++) {
duplicatedArray.push(inputArray[i]);
}
}
return duplicatedArray;
}

var arr = [2,3,4,5];
function getNumbers(num){
var j = 1;
var newArr = [];
for(var i=0; i<arr.length;i++)
{
j = 1;
while(j<=num){
newArr.push(arr[i]);
j++;
}
}
console.log(newArr.join());
}
getNumbers(4);

let multiply_array = (arr, mi = 1) =>
[].concat.apply([], arr.filter((i, ind) =>
arr.indexOf(i) == ind).map(i =>
Array(mi).fill(i)));
The multiply_array function takes two parameters, an array and the multiplying integer. It filters through the array and finds all unique values by comparing position. It then maps over all the remaining unique integers and replaces them with an array that is the length specified by the passed in multiplying integer, and filled with the unique value. All of it is concatenated together to form one array.
var oldArr = [2, 3, 4, 2, 3, 5, 6, 4, 2, 3, 2];
var newArr = [];
let multiply_array = (arr, mi = 1) =>
[].concat.apply([], arr.filter((i, ind) =>
arr.indexOf(i) == ind).map(i =>
Array(mi).fill(i)));
console.log(multiply_array(oldArr, 3));

You can do this using chain of Array.prototype methods:
var oldArr = [2,3,4,2,3,5,6,4,2,3,2];
function getNumbers(num){
return oldArr
.filter((elem, index, arr) => !arr.slice(index + 1).includes(elem))
.sort((prev, next) => next < prev)
.reduce((result, elem) => result.concat(Array(num).fill(elem)), [])
}
console.log(getNumbers(2));
console.log(getNumbers(3));

Related

Find all unique values in array and than split it and return something else

My goal is to find all the unique years in this array and than return it as a array. I have almost done it but cant figure out how I will return the split value.
function findUniqueYears() {
const arr = ['1973-11-01', '2001-01-01', '1999-10-01', '2007-10-01', '2016-06-01', '2005-08-01', '1973-09-01', '1979-12-01', '2001-08-01'];
for (var i = 0; i < arr.length; i++) {
for (var j = i + 1; j < arr.length; j++) {
if (arr[i].split("-")[0] === arr[j].split("-")[0]) {
arr.splice(j, 1);
}
}
}
console.log(arr)
}
This should do
const findUniqueYears = (arr) => Array.from(new Set(arr.map(item => item.split('-')[0])))
You can use the function map to iterate via each element in the array then you can easily split date by '-' return 0 value and cast it to Set.
function findUniqueYears() {
const arr = ['1973-11-01', '2001-01-01', '1999-10-01', '2007-10-01', '2016-06-01', '2005-08-01', '1973-09-01', '1979-12-01', '2001-08-01'];
return new Set(arr.map((el) => el.split('-')[0]))
}

Function that creates an array with subarries

I have a function which creates an array of subarrays. It takes three parameters: the number of subarries to create within the array (numSub), the number of times the desired value occurs within each subarray (numValue), and the desired value (value).
For example, if I were to call the function with (3, 2, test), I would want the following output:
Array [Array ["test", "test"], Array ["test", "test"], Array ["test", "test"]]
Here is the function I have written:
function subarrs(numSub, numValue, value) {
let arr = [];
for (let i = 0; i < numSub; i++) {
arr.push([]);
}
arr.forEach(function(sub) {
sub.fill(value, 0, numValue - 1);
});
return arr;
}
console.log(subarrs(3, 2, 'test'));
I have looped through the numSub variable and inserted an array into arr for each iteration. This was successful. (Array [Array [], Array [], Array []])
I then use a forEach loop to fill each sub-array with value beginning at index 0 and ending at index numValue - 1 (because the second occurrence of the value would actually be at index 1.)
The function does not work as intended, however. Rather than the aforementioned desired output, I receive this:
Array [Array [], Array [], Array []]
You can use fill on an array that has received the right length, like Array(numValue).fill(numValue). Here is how you could do it:
function subarrs(numSub, numValue, value) {
return Array.from({length: numSub}, () => Array(numValue).fill(value));
}
console.log(subarrs(3, 2, 'test'));
You are filling an empty array. It's still an empty array (nothing to fill).
You should construct the array of some length:
arr.push(new Array(numValue));
Complete:
function subarrs(numSub, numValue, value) {
let arr = [];
for (let i = 0; i < numSub; i++) {
arr.push(new Array(numValue));
}
arr.forEach(function(sub) {
sub.fill(value);
});
return arr;
}
console.log(subarrs(3, 2, 'test'));
Array.fill() only modifies array values. It does not add new ones. Use push again instead
function subarrs(numSub, numValue, value) {
let arr = [];
for (let i = 0; i < numSub; i++) {
arr.push([]);
}
arr.forEach(function(sub) {
for (let j = 0; j < numValue; j++) {
sub.push(value);
}
});
return arr;
}
console.log(subarrs(3, 2, 'test'));
You can use .push method to add value into your array instead .fill, see working demo :
function subarrs(numSub, numValue, value) {
let arr = [];
for (let i = 0; i < numSub; i++) {
arr.push([]);
for (let j = 0; j < numValue; j++) {
arr[i].push(value);
}
}
return arr;
}
console.log(subarrs(3, 2, 'test'));
fill will only work on indexes that already exist and its second parameter in your case should be the length of the array (which is the default value) and not length - 1. You can see it here:
let myEmptyArray = [];
let myFullArray = [1, 2, 3, 4];
myEmptyArray.fill(0, 0, 4);
myFullArray.fill(0, 0, 4);
console.log(myEmptyArray, myFullArray)
You could push an Array with the necessary slots already in place with new Array(numValue). Something like this:
function subarrs(numSub, numValue, value) {
let arr = [];
for (let i = 0; i < numSub; i++) {
arr.push(new Array(numValue));
}
arr.forEach(function(sub) {
sub.fill(value);
});
return arr;
}
console.log(subarrs(3, 2, 'test'));
If you have es2015+ You can do it easily :
const subarrs = (length, subLength, value) =>
[...Array(length)].map(() => [...Array(subLength)].fill(value));
subarrs(3, 2, 'test');
(Edited) after the first comment

Replicate array to certain length in javascript

I have this array [1,2,3]
I would like to be able to set its length to 7
and have this [1,2,3,1,2,3,1] as a result.
Anyone?
const arr = [1,2,3];
// Something like
arr.resize(7);
console.log(arr); // [1,2,3,1,2,3,1]
EDIT:
Based on chevybow answer below i wrote this functions to serve my needs.
// Immutable
Array.prototype.resize = function(size) {
const array = Array(size);
for(let i = 0; i < size; i++) {
array[i] = this[i%this.length];
}
return array;
}
// Mutable
Array.prototype.resize = function(size) {
const array = this.slice(0);
this.length = size;
for(let i = 0; i < size; i++) {
this[i] = array[i%array.length];
}
}
Are those ok? or you think that putting it on the chain is not a good idea, if so why?
You can use modular arithmetic to loop through up to the length of your final array and then use the index to basically loop through and push that onto a new array
Using the current array value % array.length will get you the current position of the array by progressing it in a circular motion
let num = 7;
let array = [1,2,3];
let result = [];
for(let i = 0; i < num; i++){
result.push(array[i%array.length]);
}
console.log(result)
A simple while loop would suffice:
function repeat(arr, toLength) {
let output = [...arr];
while (output.length < toLength) output = [...output, ...arr];
return output.slice(0, toLength);
}
console.log(repeat([1, 2, 3], 7));
console.log(repeat([1, 2, 3], 2));
How about this version:
const nums = [1, 2, 3];
function resize(arr, length) {
let position = 0;
return Array.from(Array(length)).reduce((acc, _, i) => {
return acc.concat(arr[i % arr.length]);
}, []);
}
console.log(resize(nums, 7));

Understanding For loops in javascript - printing index of values in Array

I'm trying to print the indexes of values of an array. When I do this:
let a = [1,2,3,4,5];
var findIdx = function (arr) {
for (let i = 0 ; i < arr.length; i++) {
var indexes = [];
var index = arr[i];
console.log(index);
return indexes.push(index);
}
return indexes;
}
console.log(findIdx(a));
// => 0,1 // return
Which is not what I want, I would like to get the index of those values. Furthermore, my return is returning 1. I would like an array made of those indexes. What am I missing?
When I do a for in loop I get what I want on my console, but I'm still returning the value where that index is found.
let a = [1,2,3,4,5];
var findIdxWithForIn = function (arr) {
var indexes = [];
for (i in arr) {
var index = i;
console.log(index);
return indexes.push(index);
}
return indexes
}
console.log(findIdxWithForIn(a));
// => 0, 1 // return
TL;DR: Here is a jsfiddle with the above code.
Note that I would like just to all the indexes inside that array
You are printing var index which is not an index it is element in array:
var index = arr[i];
console.log(index);
You need to get index so var index = i;. Because i in for loop is actual index. You can also use arr.indexOf(...); to get index of specific element.
You should do something like this,
var findIdxWithForIn = function (arr) {
var indexes = [];
for (i in arr) {
var index = i;
indexes.push(index)
console.log(index);
}
return indexes;
}
Now in case you want to find out what the indexes array contains then again you have put that in a for loop and extract
indexes.push(index) Should be inside for loop. You were doing it wrong.
var findIdxWithForIn = function (arr) {
var indexes = [];
for (i in arr) {
var index = i;
indexes.push(index)
}
return indexes;
}
console.log(findIdxWithForIn(a));
Try this out
let a = [1, 2, 3, 4, 5];
console.log('======= For Loop ========')
/*
For loop
*/
var findIdx = function (arr) {
var indexes = [];
for (let i = 0 ; i < arr.length; i++) {
var index = arr[i];
console.log(index);
indexes.push(index);
}
return indexes
}
console.log(findIdx(a));
console.log('======= For In ========')
/*
For In Loop
*/
var findIdxWithForIn = function (arr) {
var indexes = [];
for (i in arr) {
var index = i;
console.log(index);
indexes.push(index);
}
return indexes //.push(index);
}
console.log(findIdxWithForIn(a));

Get elements that has no double value in an array

I have a question . How do you retrieve elements that has no double value in an array?? For example: [1,1,2,2,3,4,4,5] then you retrieve [3,5] only.
Thanks in advance
for (var j = 0; j < newArr.length; j++) {
if ((arr1.indexOf(newArr[j]) === 0) && (arr2.indexOf(newArr[j]) === 0)) {
index = newArr.indexOf(j); newArr.splice(index, 1);
}
}
If the item in the array is unique then the index found from the beginning should equal the index found from the end, in other words:
var xs = [1, 1, 2, 2, 3, 4, 4, 5];
var result = xs.filter(function(x) {
return xs.indexOf(x) === xs.lastIndexOf(x);
});
console.log(result); //=> [3, 5]
sorry for the presentation its my first post !
You have to compare each element of your array to the others in order to get the number of occurence of each element
var tab = [1,1,2,2,3,4,4,5] //The array to analyze
tab = tab.sort(); // we sort the array
show(tab); // we display the array to the console (F12 to open it)
var uniqueElementTab = []; // this array will contain all single occurence
var sameElementCounter = 0;
for(x=0;x<tab.length;x++){ // for all element in the array
sameElementCounter = 0;
for(y=0;y<tab.length;y++){ // we compare it to the others
if((tab[x]==tab[y])){
sameElementCounter+=1; // +1 each time we meet the element elsewhere
}
}
if(sameElementCounter<=1){
uniqueElementTab.push(tab[x]); //if the element is unique we add it to a new array
}
}
show(uniqueElementTab); // display result
function show(tab) { // Simple function to display the content of an array
var st="";
for(i=0;i<tab.length;i++){
st += tab[i]+" ";
}
console.log(st+"\n");
}
Hope it helps.
Here is a simple "tricky" solution using Array.sort, Array.join, Array.map, String.replace and String.split functions:
var arr = [1, 1, 2, 2, 3, 4, 4, 5];
arr.sort();
var unique = arr.join("").replace(/(\d)\1+/g, "").split("").map(Number);
console.log(unique); // [3, 5]
create new array tmp,and check already value exist by indexOf .If existed delete by splice function..
var arr = [1,1,2,2,3,4,4,5];
var tmp = [];
var dup = [];
for(var i = 0; i < arr.length; i++){
var ind = tmp.indexOf(arr[i]);
if(ind == -1){
if(dup.indexOf(arr[i]) == -1){
tmp.push(arr[i]);
}
}
else{
tmp.splice(ind,1);
dup.push(arr[i]);
}
}
console.log(tmp);
This would be my way of doing this job.
var arr = [1,1,2,2,3,4,4,5],
uniques = Object.keys(arr.reduce((p,c) => (c in p ? Object.defineProperty(p, c, {enumerable : false,
writable : true,
configurable : true})
: p[c] = c,
p), {}));
console.log(uniques);
A solution for unsorted arrays with a hash table for the items. Complexity O(2n)
var array = [1, 1, 2, 2, 3, 4, 4, 5, 1],
hash = Object.create(null),
single;
array.forEach(function (a, i) {
hash[a] = a in hash ? -1 : i;
});
single = array.filter(function (a, i) {
return hash[a] === i;
});
console.log(single);
If the array is sorted, you can solve this in O(n) (see "pushUniqueSinglePass" below):
function pushUniqueSinglePass(array, unique) {
var prev; // last element seen
var run = 0; // number of times it has been seen
for (var i = 0; i < array.length; i++) {
if (array[i] != prev) {
if (run == 1) {
unique.push(prev); // "prev" appears only once
}
prev = array[i];
run = 1;
} else {
run++;
}
}
}
function pushUniqueWithSet(array, unique) {
var set = new Set();
for (var i = 0; i < array.length; i++) {
set.add(array[i]);
}
for (let e of set) {
unique.push(set);
}
}
// Utility and test functions
function randomSortedArray(n, max) {
var array = [];
for (var i = 0; i < n; i++) {
array.push(Math.floor(max * Math.random()));
}
return array.sort();
}
function runtest(i) {
var array = randomSortedArray(i, i / 2);
var r1 = [],
r2 = [];
console.log("Size: " + i);
console.log("Single-pass: " + time(
pushUniqueSinglePass, array, r1));
console.log("With set: " + time(
pushUniqueWithSet, array, r2));
// missing - assert r1 == r2
}
[10, 100, 1000, 10000,
100000, 1000000
].forEach(runtest);
function time(fun, array, unique) {
var start = new Date().getTime();
fun(array, unique);
return new Date().getTime() - start;
}
This is much more efficient than using maps or sorting (time it!). In my machine, a 1M sorted array can have its unique elements found in 18 ms; while the version that uses a set requires 10x more.

Categories