Add pattern to an array without push() - javascript

Is there a way to code this without using any methods?
a is an array, n is the number of times the pattern is repeated in the new array
const func = (a, n) => {
const arr = [];
for (let i = 0; i < n; i++) {
arr.push(...a);
}
console.log(arr);
};
func([1, 2, 3, 4], 2);

You could take a separate index and assign the values.
const func = (a, n) => {
let array = [],
i = 0;
while (n--) for (const v of a) array[i++] = v;
return array;
};
console.log(...func([1, 2, 3, 4], 2));

Well, you could use two loops and directly assign ith array item.
const func = (a, n) => {
const arr = [];
for (let i = 0; i < n; i++) {
for (let j = 0; j < a.length; j++) {
arr[i * a.length + j] = a[j]
}
}
console.log(arr);
};
func([1, 2, 3, 4], 2);

that ?
const func=(a, n)=>
{
const arr = []
let p = 0
for (let i=0;i<n;++i) for(let v of a) arr[p++] = v
console.log(JSON.stringify(arr));
}
func([1, 2, 3, 4], 2);

You could use the spread operator to create a new array for each iteration of the loop. This would mean that your arr variable can't be a constant though since it gets overwritten with a new array.
const func = (a, n) => {
let arr = [];
for (let i = 0; i < n; i++) {
arr = [...arr, ...a];
}
console.log(arr);
};
func([1, 2, 3, 4], 2);

Related

Array Difference, nested For Loops

function arrayDiff(a, b) {
let result = [];
for (let i = 0; i < a.length; i++) {
for (let j = 0; j < b.length; j++) {
if (a[i] !== b[j]) {
result.push(a[i]);
}
}
}
return result;
}
console.log(arrayDiff([1,2,2,3], [1])); // output: [2,2,3]
console.log(arrayDiff([1,2,2,3], [1,2])); // output: [1,2,2,3,3] // desired output: [3]
Trying to solve Array Difference, multiple items inside 'b' causing unwanted output.
Consider using a Set and Array#filter.
const
arr1 = [1, 5, 3, 7, 9],
arr2 = [5, 1, 10, 13],
s = new Set(arr2),
res = arr1.filter((a) => !s.has(a));
console.log(res);

Writing my own reverse array function without defining a new empty array

I am trying to write a function which reverses the elements of an array without defining a new empty array in the function.
let arrayValue = [1, 2, 3, 4, 5]
function remove(array, index) {
return array.slice(0, index).concat(array.slice(index + 1));
}
function reverseArrayInPlace(array) {
for (i = array.length - 2; i >= 0; i--) {
let removedCharacter = array[i];
array = array.concat(removedCharacter);
array = remove(array, i);
}
return array;
}
When I console.log(reverseArrayInPlace(arrayValue)) I am getting the reverse order of [5, 4, 3, 2, 1].
However when I try to just do reverseArrayInPlace(arrayValue) and then console.log(arrayValue), I am getting [1, 2, 3, 4, 5] which is the value defined at the beginning.
Is there a way of updating the arrayValue binding in the function and then when it is console.log outside the function, it is showing the reversed order?
// show cases of even and odd lengths
const x = [1,2,3,4];
const y = [1,2,3,4,5];
for (let i = 0; i < x.length / 2; i++) {
const tmp = x[i];
x[i] = x[x.length - 1 - i];
x[x.length - 1 - i] = tmp;
}
for (let i = 0; i < y.length / 2; i++) {
const tmp = y[i];
y[i] = y[y.length - 1 - i];
y[y.length - 1 - i] = tmp;
}
console.log(x);
// [4, 3, 2, 1]
console.log(y);
// [5, 4, 3, 2, 1]
The MDN docs for Array's slice and concat methods explain that these methods return new arrays, rather than modifying the existing arrays. If you are looking for a built-in Array method for modifying arrays, splice will do the job. However, it's going to be more complicated to implement this using splice than to just use a for loop as the other answers suggest.
You could just swap values symmetrically around the midpoint of the array, like
const arr = [0,1,2,3,4];
const len = arr.length;
for(let i = 0; i < len/2; i++){
let temp = arr[i];
arr[i] = arr[len-1-i];
arr[len-1-i] = temp;
}
console.log(arr);
function reverseArrayInPlace(array) {
for (let i = 0; i < array.length / 2; i++) {
const oppositeArrayIndex = array.length - (i + 1);
const oppasiteArrayValue = array[oppositeArrayIndex];
array[oppositeArrayIndex] = array[i];
array[i] = oppasiteArrayValue;
}
}

How to get all substrings (contiguous subsequences) of my JavaScript array?

My task is to split the given array into smaller arrays using JavaScript. For example [1, 2, 3, 4] should be split to [1] [1, 2] [1, 2, 3] [1, 2, 3, 4] [2] [2, 3] [2, 3, 4] [3] [3, 4] [4].
I am using this code:
let arr = [1, 2, 3, 4];
for (let i = 1; i <= arr.length; i++) {
let a = [];
for (let j = 0; j < arr.length; j++) {
a.push(arr[j]);
if (a.length === i) {
break;
}
}
console.log(a);
}
And I get the following result: [1] [1, 2] [1, 2, 3] [1, 2, 3, 4] undefined
What am I missing/doing wrong?
For the inner array, you could just start with the index of the outer array.
var array = [1, 2, 3, 4],
i, j, l = array.length,
result = [];
for (i = 0; i < l; i++) {
for (j = i; j < l; j++) {
result.push(array.slice(i, j + 1));
}
}
console.log(result.map(a => a.join(' ')));
.as-console-wrapper { max-height: 100% !important; top: 0; }
You have two issues in your code:
You need to have loop to initialize with the value of i for the inner loop so that it consider the next index for new iteration of i
You need to remove that break on the length which you have in inner loop.
let arr = [1, 2, 3, 4];
for (let i = 0; i <= arr.length; i++) {
let a = [];
for (let j = i; j < arr.length; j++) {
a.push(arr[j]);
console.log(a);
}
}
Try this
let arr = [1, 2, 3, 4];
for (let i = 0; i <= arr.length; i++) {
let a = [];
for (let j = i; j < arr.length; j++) {
a.push(arr[j]);
console.log(a);
}
}
If you don't want to mutate your array.
let arr = [1, 2, 3, 4];
let res = [];
for (let i = 0; i <= arr.length; i++) {
let a = [];
for (let j = i; j < arr.length; j++) {
a = [...a, arr[j]];
res = [...res, a];
}
}
console.log(res);
i have prepare stackblitz for this case.
let source = [1,2,3,4];
const output = [];
const arrayMultiplier = (source) => {
const eachValueArray = [];
source.forEach((item, index) => {
// Will push new array who will be sliced source array.
eachValueArray.push(source.slice(0, source.length - index));
});
//We reverse array to have right order.
return eachValueArray.reverse();
};
for(let i = 0; i <= source.length; i++) {
output.push(...arrayMultiplier(source));
source.shift(); // Will recraft source array by removing first index.
}
//Don't forget last item.
output.push(source);
console.log(output);
Is not the most shorten solution but do the job
== update after code review ==
// [...]
const arrayMultiplier = (source) => {
// Will push new array who will be sliced source array.
// We reverse array to have right order.
return source.map((item, index) => source.slice(0, source.length - index)).reverse();
};
// [...]
Use two iteration
get slice array based on loop index.
use sliced array and combine array element.
var arr = [1, 2, 3, 4];
let newArra =[];
arr.map((x,i)=> {
let remainArr = arr.slice(i);
return remainArr.forEach((y, r) => newArra.push(remainArr.slice(0, r+1)))
})
newArra.forEach(x=> console.log(x))

What is the difference between [4,null,6] and [4,6]

Here is the question:
Compare two arrays and return a new array with any items only found in one of the two given arrays, but not both. In other words, return the symmetric difference of the two arrays.
And here is my code:
function diffArray(arr1, arr2) {
var newArr = [];
// Same, same; but different.
for (i = 0; i < arr1.length; i++) {
for (j = 0; j < arr2.length; j++)
while (arr1[i] === arr2[j])
delete arr2[j];
newArr = arr2;
}
return newArr;
}
console.log(diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]));
Please, tell me my mistakes.
If you work using indices as references which you delete, you'll leave those indices undefined.
You have to use push to add an item and splice to remove one.
The time complexity of the following code should be: O(nm) where n and m are the lengths of the arr1 and arr2 arrays respectively.
function diffArray(arr1, arr2) {
var newArr = [];
for (i = 0; i < arr1.length; i++) {
for (j = 0; j < arr2.length; j++)
while (arr1[i] === arr2[j])
arr2.splice(j, 1);
newArr = arr2;
}
return newArr;
}
console.log(diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]));
This should work, but I've found a different way that is a bit slower for short arrays but much faster for longer array.
The time complexity of the following code should be: O(3(n + m)), which is reduced to O(n + m) where n and m are the lengths of the arr1 and arr2 arrays respectively.
Look at this fiddle.
Here's it:
function diffArray(arr1, arr2) {
let obj1 = {}, obj2 = {};
for (let l = arr1.length, i = 0; i < l; i++)
obj1[arr1[i]] = undefined;
for (let l = arr2.length, i = 0; i < l; i++)
obj2[arr2[i]] = undefined;
let a = [];
for (let arr = arr1.concat(arr2), l = arr.length, i = 0, item = arr[0]; i < l; i++, item = arr[i])
if (item in obj1 !== item in obj2)
a.push(item);
return a;
}
console.log(diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]));
The task you are trying to complete asks you to create a new array, but instead you modify arr2. It would probably be easiest to just copy all elements not included in the other array to a new array, like this:
function diffArray(arr1, arr2) {
var newArray = [];
arr1.forEach(function(el) {
if (!arr2.includes(el)) {
newArray.push(el);
}
});
arr2.forEach(function(el) {
if (!arr1.includes(el)) {
newArray.push(el);
}
});
return newArray;
}
If you would rather try and fix your code instead, I can try to have another look at it.
I've used Array.prototype.filter method:
function diffArray(arr1, arr2) {
var dif01 = arr1.filter(function (t) {
return arr2.indexOf(t) === -1;
});
var dif02 = arr2.filter(function (t) {
return arr1.indexOf(t) === -1;
});
return (dif01).concat(dif02);
}
alert(diffArray([1, 2, 3, 6, 5], [1, 2, 3, 4, 7, 5]));
If you still want to use your code and delete the common elements, try to use Array.prototype.splice method instead of delete: the latter deletes the value, but keeps the index empty, while Array.prototype.splice will remove those whole indices within the given range and will reindex the items next to the range.
You can use Array.prototype.filter:
var array1 = [1, 2, 3, 5];
var array2 = [1, 2, 3, 4, 5];
var filteredArray = filter(array1, array2).concat(filter(array2, array1));
function filter(arr1, arr2) {
return arr1.filter(function(el) { return arr2.indexOf(el) < 0; });
}
Here is a working JSFiddle.
Try this:
function diffArray(arr1, arr2) {
var ret = [];
function checkElem(arrFrom, arrIn) {
for (var i = 0; i < arrFrom.length; ++i) {
var elem = arrFrom[i];
if (arrIn.indexOf(elem) === -1)
ret.push(elem);
}
}
checkElem(arr1, arr2);
checkElem(arr2, arr1);
return ret;
}
I hope this can solve your problem.

How to find diff between array and array of arrays

x = [1, 2,3, 5]; y = [1, [2], [3, [[4]]],[5,6]]));
I have to find the difference between these 2 arrays.
function arr_diff (a1, a2) {
var a = [], diff = [];
for (var i = 0; i < a1.length; i++) {
a[a1[i]] = true;
}
for (var i = 0; i < a2.length; i++) {
if (a[a2[i]]) {
delete a[a2[i]];
} else {
a[a2[i]] = true;
}
}
for (var k in a) {
diff.push(k);
}
return diff;
};
This is what I tried but since it has array of arrays, this not working for me.
Can anyone please suggest help.
You could just flatten the arrays before you find the difference
function arr_diff(a1, a2) {
a1 = a1.toString().split(',');
a2 = a2.toString().split(',');
if (a1.length < a2.length) {var t = a1; a1 = a2; a2 = t};
return a1.filter( x => (!a2.includes(x)) ).map(Number);
}
var x = [1, 2,3, 5];
var y = [1, [2], [3, [[4]]],[5,6]];
var r = arr_diff(x,y);
console.log(r);
You definitely need to flatten all the arrays you want to compare using a function found here.
After flattening them, you can compare them using a function found here
let x = [1, 2,3, 5];
let y = [1, [2], [3, [[4]], [5,6] ]]
const flatten = list => list.reduce(
(a, b) => a.concat(Array.isArray(b) ? flatten(b) : b), []
)
const difference = (arr1,arr2) => {
arr1 = flatten(arr1)
arr2 = flatten(arr2)
return arr1.filter(e => arr2.indexOf(e) === -1)
.concat(arr2.filter(e => arr1.indexOf(e) === -1))
}
console.log(difference(x,y)) // [4,6]

Categories

Resources