How to remove element from array using javascript - javascript

I have 2 array and want to remove the elements of 2nd array as per position numbers on 1st array.
var notexists = []; //value is "1","5","8" on 0,1,2nd position.
var copyrequiredfields = [];//Value is "a","b","c","d","e","f",...
for (var i = 0; i < notexists.length; i++) {
copyrequiredfields.splice(parseInt(notexists[i]), 1);
}
as per example i want to remove 1st 5th and 8th element from copyrequiredfields .
Please suggest some answer.

Create a new array, iterate the copyrequiredfields, when the index in notexists, ignore it.
example:
var notexist = [1,2,5];
var copyrequiredfields = ['a','b','c','d','e','f','g'];
//create a index map
var index_map = {};
for(var i = 0; i < notexist.length; i++){
index_map[notexist[i]] = true;
}
//remove the elements
var newarray = [];
for(var i = 0; i < copyrequiredfields.length; i++){
if(!index_map[i]){
newarray.push(copyrequiredfields[i]);
}
}
copyrequiredfields = newarray;

In JS, index of array starts with 0 and not 1 so you just have to subtract 1 from value before splice. Rest of the code is fine.
One issue is, as you remove elements from array, elements after it are moved 1 position back. This will give you incorrect output. 1 hack is to count number of elements removed to count movement.
A better solution would be to use array.filter.
Array.splice
var notexists = ["1", "5", "8"]; //value is on 0,1,2nd position.
var copyrequiredfields = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]; //Value is "a","b","c","d","e","f",...
var count=0;
for (var i = 0; i < notexists.length; i++) {
console.log(+notexists[i] - 1)
copyrequiredfields.splice(+notexists[i]-1-count++, 1);
}
console.log(copyrequiredfields)
Array.filter
var notexists = ["1", "5", "8"]; //value is on 0,1,2nd position.
var copyrequiredfields = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]; //Value is "a","b","c","d","e","f",...
var r = copyrequiredfields.filter((x,i)=>notexists.indexOf((i+1).toString()) === -1)
console.log(r)

You could copy the whole array, except of the parts you dont need anymore:
var tempCopy = [];
for (var i=0; i < copyrequiredfields.length; i++)
if(notexists.indexOf(i)==-1)
tempCopy.push(copyrequiredfields[i]);
copyrequiredfields = tempCopy;
Greets!

Related

How to remove items from list that were pushed

I am trying to remove only items that were pushed into a list so that I am only left with the original list items
const list = ["a", "b", "c", "d"];
for (let i = 0; i < 4; i++) {
list.push(i);
}
console.log(list);
// outputs: a,b,c,d,1,2,3,4 // as expected
// how can we remove only the pushed items.
list.pop;
console.log(list);
// outputs : []
// desired output: a,b,c,d
I'm not sure what your case is and why you want to extract the items from the array but anyway.
The first option would be: duplicating the array into another variable
or the second option: extracting it using splice when you know the length of the original array.
Snippets:
const list = ["a", "b", "c", "d"];
const original = list.slice(); // duplicating array
const originalLength = list.length // getting original length
for (let i = 0; i < 4; i++) {
list.push(i);
}
console.log("original1: ", original);
console.log("original2: ", list.slice(0, originalLength));
You can remove the elements from the index where you have begun pushing new elements using splice.
const list = ["a", "b", "c", "d"];
for (let i = 0; i < 4; i++) {
list.push(i);
}
list.splice(list.length - 4)
console.log(list);
If you need two to have one "for loop" pushing items into an array, and then remove those same items in another loop, then a simple solution would be
Snippet:
const list = ["a", "b", "c", "d"];
for (let i = 0; i < 4; i++) {
list.push(i);
}
for (let j of list) {
if (j) {
list.pop();
}
};
console.log(list);

nested for each loop to insert value which in array without duplication and loop start from first

Example
If my values are in array like this
var myPlaces = ["a", "b", "c"];
var friendPlaces = ["d", "0", "e"];
for(var i = 0; i < myPlaces.length; i++) {
console.log(myPlaces[i]);
for(var j = 0; j < friendPlaces.length; j++) {
if (myPlaces[i] == friendPlaces[i]) {
console.log(myPlaces[i]);
};
I need answer as
(a,d)(b,0)(c,e) as three result but it gives count more than 3
help me to modify my current answer (a,d) (d,a) (d,b) (d,c) then (b,o)
You can use Array#map (Assuming your input arrays are of same length with fixed count of arrays- i.e. 2 in your case).
If you use map on myPlaces then 1st parameter is current value of myPlaces in loop and the 2nd parameter is index of that element in array. So you can match current element in myPlaces with elements from friendPlaces array with the same index using this index.
var myPlaces = ["a", "b", "c"];
var friendPlaces = ["d", "0", "e"];
var result = myPlaces.map((e, i) => "("+e +","+ friendPlaces[i]+")");
console.log(result);

Merging of array in javascript or jquery

var first = [ "a", "b", "c" ];
var second = [ "d", "e", "f" ];
My output should be
var final=["a~d","b~e","c~f"];
where '~' is delimiter.
Check if the length of both arrays.
See comments inline in the code:
var first = [ "a", "b", "c" ];
var second = [ "d", "e", "f" ];
var len = first.length > second.length ? first.length : second.length;
// Get the length of the array having max elements
var separator = '~';
var final = [];
for(var i = 0; i < len; i++) {
// If no element is present, use empty string
first[i] = first[i] ? first[i] : '';
second[i] = second[i] ? second[i] : '';
final.push(first[i] + separator + second[i]);
// Add the new element in the new array
}
Here is a function for this... you can specify the behavior, if the arrays are not the same length:
function merge(arr1,arr2,delimiter){
var i,len;
var delim = delimiter.toString();
var res = [];
if(arr1.length !== arr2.length){
//TODO: if arrays have different length
}else{
len = arr1.length;
for(i=0; i< len; i++){
res[i] = arr1[i] + delim + arr2[i];
}
}
return res;
}
merge(['a','b','c'],['d','e','f'],'~');
This is exactly what Haskell's zipWith function does. It takes a function (which takes two arguments and does something with them to return only one value) and two arrays, looping through the arrays and passing it's values into the function.
Here is a non-recursive example:
var zipWith = function(zippingFunction, arr1, arr2){
var length = arr1.length < arr2.length ? arr1.length : arr2.length;
var retArray = [];
for (i = 0; i< length; i++){
retArray.push(zippingFunction(arr1[i], arr2[i]));
}
return retArray;
};
console.log(zipWith(function(a, b){return a + b}, [1,2,3], [4,5,6]));
console.log(zipWith(function(a, b){return a + "~" + b}, ["1","2","3"], ["4","5","6"]));
Which returns:
[ 5, 7, 9 ]
[ '1~4', '2~5', '3~6' ]
var first = [ "a", "b", "c" ];
var second = [ "d", "e", "f" ];
var final=[];
// assuming they are the same length
for(var i = 0; i < first.length; i++) {
final.push(first[i] + '~' + second[i]);
}
console.log(final);
var first = [ "a", "b", "c" ];
var second = [ "d", "e", "f" ];
var count = -1;
var arr=new Array();
first.forEach(function(entry) {
count++;
arr[count] = entry + "~" + second[count];
});
alert(arr);
Use Like This You Get Your Desired Result
Demo is Here http://jsfiddle.net/7evx02zf/6/
var final1=[];
var first = [ "a", "b", "c" ];
var second = [ "d", "e", "f" ];
$.each(first, function( index, value ) {
var tmp=value+"~"+second[index];
final1[index]=tmp;
});
console.log(final1);
JQUERY only solution.Try this,should work.
Try this...
<script>
var first = ["a", "b", "c"];
var second = ["d", "e", "f"];
var third=new Array();
for(i=0;i<first.length;i++)
{
var data=first[i]+'~'+second[i];
third.push(data);
}
console.log(third);
</script>
Output:["a~d", "b~e", "c~f"]
A JavaScript only solution.
Try this. This solution assumes that both arrays are equal in length.
//your initial array
var first = [ "a", "b", "c" ];
var second = [ "d", "e", "f" ];
//set up final array
var final = [];
//loop through
for (var ii = 0, nn = first.length; ii < nn; ii++)
{
//add to final array each item of first and secon
final.push(first[ii]+"~"+second[ii]);
}
//print to console
console.log(final);
Output:
["a~d", "b~e", "c~f"]
If you're not sure if length are the same, this will go up to the shortest
//your initial array
var first = [ "a", "b", "c", "g" ];
var second = [ "d", "e", "f" ];
//set up final array
var final = [];
//loop through until the length of shortest
for (var ii = 0, nn = (first.length < second.length ? first.length : second.length); ii < nn; ii++)
{
//add to final array each item of first and secon
final.push(first[ii]+"~"+second[ii]);
}
//print to console
console.log(final);
Output:
["a~d", "b~e", "c~f"]
Try this code:
var final=[];
var first = [ "a", "b", "c" ];
var second = [ "d", "e", "f" ];
for(var i = 0; i < first.length; i++) {
final.push(first[i] + '~' + second[i]);
}
console.log(final.toString());
Example:
Click Here for Demo
You could try this JS only solution. It's only 1 line and works regardless of both first and second lengths:
var first = [ "a", "b", "c", "x", "y" ];
var second = [ "d", "e", "f" ];
var final = [];
first.forEach(function(v,i) {final[i] = first[i] + '~' + (second[i] || '')});

How might I return multiple arrays with equal values from a larger array with mixed values?

I have an array that after being sorted appears like this:
var arr = ["a", "a", "b", "b", "b", "b", "c", "c", "c"];
There are 2 "a" Strings, 4 "b" Strings, and 3 "c" Strings.
I am trying to return 3 separate arrays, returning them one at a time from a loop, containing only matching values. So, upon the first iteration, the returned array would appear as newArr = ["a", "a"], the second as newArr = ["b", "b", "b", "b"] and on the third iteration as newArr = ["c", "c", "c"].
However, this is a small array of predefined values, and I need an algorithm that can perform the same operation on an array of unknown size, unknown elements, and with an unknown number of like elements. (and keep in mind that the array is already sorted to begin with, in this context)
Here's my crazy code that is displaying some unusual, and incorrect, results:
var arr = ["a", "a", "b", "b", "b", "b", "c", "c", "c"];
for(var index = 0; index < arr.length; index++)
{
var test = "";
var newArr = []; // resets the new array upon each iteration
var str = arr[index]; // initialized as the next unique index-value
for(var i = index; i < arr.length; i++)
{
if(arr[i] == str)
{
newArr.push(arr[k]);
test += arr[i] + " ";
}
else
{
index = i; // changing the outer loop variable
break; // exiting the inner loop
}
} // end of inner loop
window.alert(test);
setValues(newArr);
} // end of outer loop
function setValues(arrSorted)
{
var here = document.getElementById("here");
for(var i = 0; i < arrSorted.length; i++)
{
here.innerHTML += arrSorted[i] + " ";
}
here.innerHTML += "<br />";
} // end of setValues function
var arr = ["a", "a", "b", "b", "b", "b", "c", "c", "c"];
var arrays = {};
for (var i=0;i<arr.length;i++) {
if (!arrays[arr[i]]) arrays[arr[i]] = [];
arrays[arr[i]].push(arr[i]);
}
this will give you the equivalent of
arrays = {};
arrays['a'] = ['a','a'];
arrays['b'] = ['b','b','b','b','b'];
arrays['c'] = ['c','c','c'];
You can use a function like this to divide the array into several arrays:
function divide(arr) {
var subArrays = [];
var current = null;
var subArray = null;
for (var i = 0; i < arr.length; i++) {
if (arr[i] != current) {
if (subArray != null) subArrays.push(subArray);
current = arr[i];
subArray = [];
}
subArray.push(arr[i]);
}
if (subArray != null) subArrays.push(subArray);
return subArrays;
}
Demo: http://jsfiddle.net/Guffa/d8CBD/
This is how I would do it:
var arr = ["a", "a", "b", "b", "b", "b", "c", "c", "c"];
var out = [], prev;
for (var i = 0, j = 0, len = arr.length; i < len; i++) {
if (arr[i] !== prev || !out.length) {
out[j++] = [prev = arr[i]];
} else {
out[j - 1].push(prev);
}
}
//out -> [["a","a"],["b","b","b"],["c","c","c"]]
Demo
Note: the || !out.length check is just handle arrays that start with undefined correctly, but feel free to remove it if this will never be the case

Accessing objects within objects

var data = {
row: row,
row2: row2
};
var tableData = [data.row,data.row2];
row objects contains lot of children objects too... now how would i placed my tableData to access each single objects. so it goes like this...
var tableData = [data.row[1],data.row[2],data.row[3],,data.row2];
Updated Question
var data = [row, row2];
In this case how would i access my row children objects.
var data = {key: value, ... };
var tableData = [];
for (var k in data) {
for (var i = 0, len = data[k].length; i < len; i++)) {
tableData.push(data[k][i]);
}
}
Use nested for loops and array.prototype.push
Edit
for (var j = 0, len = data.length;j < len;j++) {
for (var i = 0, len = data[j].length; i < len; i++)) {
tableData.push(data[j][i]);
}
}
You can replace for (var j in data) with for (var j = 0, len = data.length; j < len; j++)
The latter
sets j to 0
caches the length so you only ask for the length once.
Checks that j is not bigger then the amount of elements in your array
Increases j when you get to the end of the block.
Assign data.row first, then push data.row2, like this:
var tableData = data.row
tableData.push(data.row2)
How about something like this...
var data = {
letters : ["a", "b", "c"],
numbers : ["0", "1", "2", "3"]
};
data.letters; // ["a", "b", "c"]
data.letters[0]; // "a"
data.numbers; // "0", "1", "2", "3"]
data.numbers[2]; // "2"
... or you could try this...
var data = {
letters : new Array("a", "b", "c"),
numbers : new Array("0", "1", "2", "3")
};
data.letters; // ["a", "b", "c"]
data.letters[0]; // "a"
data.letters.push("d"); // the array is now ["a", "b", "c"]
data.numbers; // ["0", "1", "2", "3"]
data.numbers[2]; // "2"
data.numbers.pop(); // the array is now ["0", "1", "2"]
For more info on JavaScript arrays, check out these links:
http://www.hunlock.com/blogs/Mastering_Javascript_Arrays
http://blog.xkoder.com/2008/07/10/javascript-associative-arrays-demystified/
I hope this helps.
Hristo

Categories