[JS]Array merging without using array functions - javascript

I need help merging two arrays without using any of the array built in functions ( no concat, push, pop, shift, replace, sort, splice, etc)
And I've got to this point but I'm stuck.
function addTwoArrays(arr1, arr2){
var merge = [], p;
for(p = 0; p < arr1.length; p++){
merge[arr1[p]] = true;
}
for(p = 0; p < arr2.length; p++){
merge[arr2[p]] = true;
}
return Object.keys(merge);
}
window.alert(addTwoArrays([1,2,3,4],[4,3,2,1]));
return is 1,2,3,4 - instead of 1,2,3,4,4,3,2,1

You only need to loop once - simply take arr1.length as a start index and add to the array:
function addTwoArrays(arr1, arr2) {
let start = arr1.length;
for (let i = 0; i < arr2.length; i++) {
arr1[start++] = arr2[i];
}
return arr1;
}
console.log(addTwoArrays([1, 2, 3, 4], [4, 3, 2, 1]));

Keys are unique in a JSON object. So, Object.keys() will return unique occurrences of each element.
Instead try this:
function addTwoArrays(arr1, arr2){
var merge = [], p, index = 0;
for(p = 0; p < arr1.length; p++){
merge[index++] = arr1[p];
}
for(p = 0; p < arr2.length; p++){
merge[index++] = arr2[p];
}
return merge;
}
window.alert(addTwoArrays([1,2,3,4],[4,3,2,1]));

function mergedArray(arrayOne, arrayTwo) {
let newArr = arrayOne
let x = arrayOne.length
let y = arrayTwo.length
let z = arrayOne.length + arrayTwo.length
let i, j
for (i = x, j = 0; i < z && j < y; i++, j++) {
newArr[i] = arrayTwo[j]
}
return newArr
}

Related

How to insert an array to another array at each iteration of a for loop in javascript

I have a function to bubble sort and I want to save the array after each swap into another array. The bubble sort is working properly and I can log the array after each swap to the console. But I cant seem to push to the other array properly.
Here's my code :
var arr = [5, 4, 3, 2, 1];
var steps = [];
function bubbleSort() {
for (let i = 0; i < arr.length - 1; i++) {
for (let j = 0; j < arr.length - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
swap(arr, j, j + 1);
}
var temp = arr;
console.log(temp);
steps.push(temp);
}
}
console.log(steps);
}
const swap = (a, x, y) => {
var temp = a[x];
a[x] = a[y];
a[y] = temp;
};
bubbleSort();
Here's a screenshot of the console :
screenshot of console
It's only when I try to use get a hold of the array at each step that it isn't showing properly? what do I do?
I think clonning the array could work ? var temp = [...arr];
var arr = [5, 4, 3, 2, 1];
var steps = [];
function bubbleSort() {
for (let i = 0; i < arr.length - 1; i++) {
for (let j = 0; j < arr.length - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
swap(arr, j, j + 1);
}
var temp = [...arr];
console.log(temp);
steps.push(temp);
}
}
console.log(steps);
}
const swap = (a, x, y) => {
var temp = a[x];
a[x] = a[y];
a[y] = temp;
};
bubbleSort();
You are inserting the Reference of the Temp-Array and not the actual content. This way, you store multiple times the reference and at the End you are presented with all those reference pointing to the last version of your temp Array.
You can use the destructuring assignment of an array, to create an easy shallow copy to be stored.
var arr = [5, 4, 3, 2, 1];
var steps = [];
function bubbleSort() {
for (let i = 0; i < arr.length - 1; i++) {
for (let j = 0; j < arr.length - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
swap(arr, j, j + 1);
}
var temp = arr;
console.log(temp);
// Changed to destructuring assignment
steps.push([...temp])
}
}
console.log(steps);
}
const swap = (a, x, y) => {
var temp = a[x];
a[x] = a[y];
a[y] = temp;
};
bubbleSort();

equivalent of python's array.pop() in javascript

I wonder if there's an easy to implement equivalent to python's array.pop() which returns the deleted element while deleting it from the array in parallel in javascript.
let nums = [2, 1, 3, 4, 5, 6];
function sortArray(nums) {
let arr = new Array();
let smallest_index;
for (let j = 0; j < nums.length; j++) {
smallest_index = find_smallest(nums);
console.log("smallest", smallest_index);
arr.push(nums.splice(smallest_index, 1).join(""));
}
return arr;
}
function find_smallest(arr) {
let smallest = arr[0];
let smallest_index = 0;
for (let i = 1; i < arr.length; i++) {
if (arr[i] < smallest) {
// console.log("this");
smallest = arr[i];
smallest_index = i;
}
}
return smallest_index;
}
it seems that if I replace javascript's (nums.splice(smallest_index, 1).join()) with python's (arr.append(nums.pop(smallest_index)) I would get a perfectly sorted array. is there a similar straightforward solution in javascript as well ?
OK, you use splice. Here's an example of the implementation below:
Array.prototype.pythonPop = function (index) {
return this.splice(index, 1)[0];
}
Now, I found the issue, you'll love the answer. So you were using num.length but your methods were augmenting the length of num array. Which is why your answer had only half the needed numbers. See code below. I cached the length prop of nums array
let nums = [2, 1, 3, 4, 5, 6];
function sortArray(nums) {
let arr = new Array();
let smallest_index;
console.log(nums)
for (let j = 0, length = nums.length; j < length; j++) {
smallest_index = find_smallest(nums);
console.log("smallest", smallest_index);
console.log(nums)
arr[j] = nums.splice(smallest_index, 1).join("");
}
return arr;
}
function find_smallest(arr) {
let smallest = arr[0];
let smallest_index = 0;
for (let i = 1; i < arr.length; i++) {
if (arr[i] < smallest) {
// console.log("this");
smallest = arr[i];
smallest_index = i;
}
}
return smallest_index;
}
console.log(sortArray(nums))

Conditioning a Function (JS)

I'm trying to return a message if one of the argument is not a number. Otherwise continue with the function.
I'm trying this but it's not working as I'm expecting.. ..Please, any help?
function findingPairs(arr, value){
if(isNaN(arr) || isNaN(value)){
return "Please, introduce just numbers"
}
let sum = 0;
let finalOutput = [];
for(let i = 0; i < arr.length; i++){
let numA = arr[i]
console.log(numA)
} for(let j = 1; j < arr.length; j++){
let numB = arr[j]
console.log(numB)
}
}
findingPairs([1,3,7], 9)
You can use Number.isInteger to check if something is a number.
And Array.every over the array to check all the array.
Also I'm throwing an Error instead of returning a value because that's what is expected usually.
Error Docs
function findingPairs(arr, value) {
if (!arr.every(Number.isInteger) || !Number.isInteger(value)) {
throw new Error("Please, introduce just numbers");
}
let sum = 0;
let finalOutput = [];
for (let i = 0; i < arr.length; i++) {
let numA = arr[i];
console.log(numA);
}
for (let j = 1; j < arr.length; j++) {
let numB = arr[j];
console.log(numB);
}
}
const value = findingPairs([1, 3, 7], 9);
const value2 = findingPairs([1, "a", 7], 9); // Will throw
const value2 = findingPairs([1, 23, 7], "hey"); // Will throw
console.log(value);
You need to check if each element of the array is a number, you can use Array.prototype.some() to test if one element of the array respects a condition
function findingPairs(arr, value){
if(arr.some(isNaN) || isNaN(value)){
return "Please, introduce just numbers"
}
let sum = 0;
let finalOutput = [];
for(let i = 0; i < arr.length; i++){
let numA = arr[i]
console.log(numA)
}
for(let j = 1; j < arr.length; j++){
let numB = arr[j]
console.log(numB)
}
}
findingPairs([1,3,7], 9)

Finding same element in two array using for loop without any function [duplicate]

This question already has answers here:
How to filter an array from all elements of another array
(24 answers)
Closed 4 years ago.
I have two array arr1 and arr2 I want my output like 1,2,3,4... if my arr1 and arr2 contain same number but unfortunately i get only one match
example if I put var arr1 = [1,2,3,4,5,6,7,8,9,0] & var arr2 = [ 1,2,3,4,5] then I want my output like:
1,2,3,4,5
var i, j;
var arr1 = new Array(5);
var arr2 = new Array(5);
for (i = 0; i <= 4; i++) {
arr1[i] = parseInt(prompt("Enter The arr1 Element"));
}
for (i = 0; i <= 4; i++) {
arr2[i] = parseInt(prompt("Enter The Arr2 Element"));
}
var k;
var l;
for (k = 0; k < arr1.length; k++) {
for (l = 0; l < arr2.length; l++) {
if (arr1[k] == arr2[l]) {
document.getElementById("show").innerHTML = arr1[k];
}
continue;
}
}
<html>
<head>
<title>
Common In Array[]
</title>
</head>
<body>
<p id="show"></p>
</body>
</html>
then I want my output like: 1,2,3,4,5
You are only setting one value using assignment operator =.
document.getElementById("show").innerHTML = arr1[k];
You need to push your values in an array and then show them at once after separating them with ,
var output = [];
for (k = 0; k < arr1.length; k++) {
for (l = 0; l < arr2.length; l++) {
if (arr1[k] == arr2[l]) {
output.push(arr1[k]);
}
}
}
document.getElementById("show").innerHTML = output.join(",");
Demo
var i, j;
var arr1 = new Array(5);
var arr2 = new Array(5);
for (i = 0; i <= 4; i++) {
arr1[i] = parseInt(prompt("Enter The arr1 Element"));
}
for (i = 0; i <= 4; i++) {
arr2[i] = parseInt(prompt("Enter The Arr2 Element"));
}
var k;
var l;
var output = [];
for (k = 0; k < arr1.length; k++) {
for (l = 0; l < arr2.length; l++) {
if (arr1[k] == arr2[l]) {
output.push(arr1[k]);
}
}
}
document.getElementById("show").innerHTML = output.join(",");
<p id="show"></p>
Check this out. You don't need very complex logic to acheive what you want
var arr1 = [1,2,3,4,5,6,7,8,9,0];
var arr2 = [ 1,2,3,4,5];
let res = [];
if(arr1.length >= arr2.length) {
res = arr1.filter(a => arr2.find(o => o === a));
} else {
res = arr2.filter(a => arr1.find(o => o === a));
}
console.log(res)
document.getElementById("show").innerHTML = res;
<p id="show"></p>
try this:
var outputstring = "";
for (k = 0; k < arr1.length; k++) {
for (l = 0; l < arr2.length; l++) {
if (arr1[k] == arr2[l]) {
outputstring += arr1[k] + ",";
}
continue;
}
}
document.getElementById("show").innerHTML = outputstring;
You could use filter method and compare both arrays...
let arr1 = [1,2,3,4,5];
let arr2 = [1,2,3,6,7];
let result = arr1.filter((element)=>arr2.includes(element));
console.log(result);
var array1 = [1,2,3,4,5,6,7,8,9,0];
var array2 = [1,2,3,4,5];
var results = array1.filter(function(item) {
return array2.indexOf(item) !== -1;
});
console.log(results);

Find the index of the sub-array that does not contain a number

var array = [[2,3,4],[4,5,6],[2,3,9],[7,8,1]];
var number = 3;
If I have this nested array and this variable how do I return the index of the sub-arrays where the number is present. So the final result should be 1 and 3.
Try:
array.reduce((acc, subArr, i) => {
if (!subArr.includes(number)) {
acc.push(i);
}
return acc;
}, [])
The solution using Array.prototype.forEach() and Array.prototype.indexOf() functions:
var arr = [[2,3,4],[4,5,6],[2,3,9],[7,8,1]],
number = 3,
result = [];
arr.forEach(function(v,i){
if (v.indexOf(number) === -1) result.push(i);
});
console.log(result);
function X(a){
var r = [];
for(var i = o ; i < a.length; i++)
for(var j = o ; j < a[i].length; i++)
if(a[i][j] === number)
r.push(i);
return r;
}
i think this should do it. i have just written it here so might have some syntax errors
Since the question is super inconsistent, if you want the index of the subarrays that do have the number, do this:
var foundIndices = [];
for(var y = 0;y < array.length; y++) {
for(var x = 0;x < array[y].length; x++) {
if(array[y][x] == number) {
foundIndices[foundIndices.length] = y;
}
}
}
Otherwise, do this:
var foundIndices = [];
var found = false;
for(var y = 0;y < array.length; y++) {
found = false;
for(var x = 0;x < array[y].length; x++) {
if(array[y][x] == number) {
found = true;
}
}
if(found == false) {
foundIndices[foundIndices.length] = y;
}
}

Categories

Resources