Array iterate and pop() - javascript

I'm looking for a simple method to iterate over an array and generate a result like below... Better if someone can show me how to do this in the ES2015 way.
var numbers = ['one', 'two', 'three'];
/* Expected result */
/*
0: ['one', 'two', 'three'],
1: ['one', 'two'],
2: ['one']
*/
https://jsfiddle.net/minuwan/1eL83sbz

You could map the sliced array.
var numbers = ['one', 'two', 'three'],
result = numbers.map(function (_, i, a) {
return a.slice(0, a.length - i);
});
console.log(result);

You can use slice to get the output you want instead of using pop since it will modify your numbers array
var numbers = ['one', 'two', 'three'];
var array = [];
var arrayLength = numbers.length;
for (var i = 0; i < arrayLength; i++) {
array[i] = numbers.slice(0, arrayLength - i);
}
console.log(array);
or you would simply use map with slice
var numbers = ['one', 'two', 'three']
var array = numbers.map(function (_, i) {
return numbers.slice(0, numbers.length - i);
});
console.log(array);

Related

Merge two array and if some value true add property? Javascript

I need loop thought two array and return another array with different values.
Example of two arrays:
let arr1 = ['one' , 'two' , 'three'];
let arr2 = ['four' , 'one' , 'two'];
What do I need?
Loop thought both array and return the same value, I expect new array like:
let res = [
{ name : 'one' , isSame: true },
{ name : 'two' , isSame: true },
{ name : 'three' },
{ name : 'four' }
];
I am removed the duplicate items and add isSame value to true on duplicated values.
One and two are duplicated ( twice ).
What I have tried
let arr3 = arr1.map((item, i) =>
Object.assign({}, item, arr2[i])
);
But I got a splitted array and it's removed duplicated
Reduce to an intermediate object and then map that object's entries:
const arr1 = ['one' , 'two' , 'three'];
const arr2 = ['four' , 'one' , 'two'];
const result = Object.entries([...arr1, ...arr2].reduce(
(a, v) => ({ ...a, [v]: v in a }),
{}
)).map(([name, isSame]) => ({ name, isSame }));
console.log(result);
The spreading behavior in the reduce() callback increases time complexity in favor of being more terse, but can easily be avoided, making this solution O(n):
const arr1 = ['one' , 'two' , 'three'];
const arr2 = ['four' , 'one' , 'two'];
const result = Object.entries([...arr1, ...arr2].reduce(
(a, v) => {
a[v] = v in a;
return a;
},
{}
)).map(([name, isSame]) => ({ name, isSame }));
console.log(result);
I would suggest you to use reduce() to do it
let arr1 = ['one' , 'two' , 'three'];
let arr2 = ['four' , 'one' , 'two'];
let arr3 = arr1.concat(arr2)
let result = arr3.reduce((a,c) =>{
let obj = a.find(i => i.name == c)
if(obj){
obj['isSame'] = true
}else{
a.push({'name':c})
}
return a
},[])
console.log(result)
Update:
solution without reduce(),using set() to remove duplicate elements,and using includes() to find duplicate elements
let arr1 = ['one' , 'two' , 'three'];
let arr2 = ['four' , 'one' , 'two'];
let arr3 = [...new Set(arr1.concat(arr2))]
let result = arr3.map(a =>{
let data = {'name':a}
if(arr1.includes(a) && arr2.includes(a)){
data["isSame"] = true
}
return data
})
console.log(result)
Update: Based on OP's comments,show with opposite result
let arr1 = ['one' , 'two' , 'three'];
let arr2 = ['four' , 'one' , 'two'];
let arr3 = [...new Set(arr1.concat(arr2))]
let result = arr3.map(a =>{
let data = {'name':a}
if(!arr1.includes(a) || !arr2.includes(a)){
data["isSame"] = true
}
return data
})
console.log(result)
Since you don't want reduce, you can loop through each item, and check the next few values.
This is natively faster with less function calls, just two for loops.
let arr1 = ['one', 'two', 'three'];
let arr2 = ['four', 'one', 'two'];
console.log(merge(arr1, arr2));
function merge(a, b) {
const merged = a.concat(b); // combine arrays
const result = [];
let stop = merged.length; // create a variable for when to stop
for(let i = 0; i < stop; i++) {
const current = merged[i];
let same = false;
// look through the rest of the array for indexes
for(let t = i + 1; t < stop; t++) {
if(current === merged[t]) {
same = true;
merged.splice(t, 1); // remove duplicate elements from the array so we don't come across it again
stop--; // we've removed an element from the array, so we have to stop 1 earlier
// we don't break this loop because there may be more than 2 occurences
}
}
const out = { name: current };
if(same) out.isSame = true;
result.push(out);
}
return result;
}
I have used map() function of array.
map() returns new array by performing code logic on each valid entry.
[...new Set([...arr1, ...arr2])], this will return new array with unique values.
I am assuming, that you are checking if value is in both array or not and based upon that we are returning object.
let arr1 = ['one', 'two', 'three'];
let arr2 = ['four', 'one', 'two'];
let mergedArray = [...new Set([...arr1, ...arr2])];
let result = mergedArray.map(value => {
if (arr1.includes(value) && arr2.includes(value)) {
return {
value,
isInBothArray: true
}
} else {
return {
value,
isInBothArray: false
}
}
});
console.log(result);
const arr1 = ['one' , 'two' , 'three'];
const arr2 = ['four' , 'one' , 'two'];
// returns the duplicate values in the two arrays
const findDuplicates = (arr) => {
let sorted_arr = arr.slice().sort();
let results = [];
for (let i = 0; i < sorted_arr.length - 1; i++) {
if (sorted_arr[i + 1] == sorted_arr[i]) {
results.push(sorted_arr[i]);
}
}
return results;
}
let values = ([...new Set([...arr1, ...arr2])]);
let duplicates = findDuplicates(values);
let retval = [];
for(let i = 0; i < values.length; i++) {
let isSame = duplicates.includes(values[i]);
retval.push({name: values[i], isSame: isSame})
}
const arr1 = ['one', 'two', 'three'];
const arr2 = ['four', 'one', 'two'];
const result = Array.from(new Set(arr1.concat(arr2))).reduce((p, c) => {
const obj = { name: c };
if (arr1.concat(arr2).join("").split(c).length - 1 > 1) obj.isSame = true;
p.push(obj)
return p;
}, []);
console.log(result);

How can the first element be compared to the rest of the elements and the second element to the rest of the elements and the same repetition

I want compare between elements in the same array to get this result
let arr = ['one','two','three','four'];
arr.forEach((ele, i, ar)=>{
console.log(ele, i, ar)
for(let item = i; item< ar.length; item++ ){
console.log (ele, ar[item])
}
})
'one' => 'two',
'one' => 'three',
'one' => 'four',
'two' => 'three',
'two' => 'four',
'three' => 'four'.
You can use two for loop, and make the second loop start from the index of the first loop + 1:
let arr = ['one','two','three','four'];
for(let i=0; i< arr.length; i++){
for(j=i+1; j<arr.length; j++){
console.log(arr[i],' => ', arr[j]);
}
}
Use flatMap and slice
let arr = ["one", "two", "three", "four"];
const res = arr.flatMap((x, i) => arr.slice(i + 1).map(y => `${x} => ${y}`));
console.log(res)

str.reverse function reversing every array in global scope

Can't tell if my browser console is bugged, or what is going on, as I've never had issues using the reverse function.
When I throw the following into my chrome console,
var a = ['one', 'two', 'three'];
var reversed = a.reverse();
console.log(a); // ['one', 'two', 'three']
console.log(reversed); // ['three', 'two', 'one']
I get
Array#reverse works in place and doesn't create a new array. The line
var reversed = a.reverse();
reverses a and also sets reversed to reference the same array.
In this example you can see that adding an item to reversed also affects a because they reference the same array:
var a = ['one', 'two', 'three'];
var reversed = a.reverse();
reversed.push(1000); // add something to reversed
console.log(a); // ['three', 'two', 'one', 1000]
console.log(reversed); // ['three', 'two', 'one', 1000]
To create a new array use Array#slice on the original, and then reverse the array:
var a = ['one', 'two', 'three'];
var reversed = a.slice().reverse();
console.log(a); // ['one', 'two', 'three']
console.log(reversed); // ['three', 'two', 'one']
The reverse function mutates the current array. After you declare reversed to be a.reverse(), the array a will be mutated as well. Thus, you will print out ['three', 'two', 'one'] for console.log(a) and console.log(reversed)
What you want to do is to make a clone of a:
var a = ['one', 'two', 'three'];
var reversed = a.slice().reverse();
console.log(a); // ['one', 'two', 'three']
console.log(reversed); // ['three', 'two', 'one']

combining two separate arrays into one array with objects

I have two separate arrays which looks something like this
var x = ['one', 'two', 'three'];
var y = ['1', '2', '3'];
I am doing this to combine them
var newArray = [];
for (var i = 0; i < x.length && i < y.length; i++) {
newArray[i] = [x[i], y[i]];
}
desired output
newArray = [
['one', '1'],
['two', '2'],
['three', '3']
]
This is my fiddle: http://jsfiddle.net/sghoush1/EjRPS/4/
On ES5 you can use Array.prototype.map to simplify your loop:
var newArray = x.map(function(n, i) {
return [n, y[i]];
});
See the above link for a shim for older browsers.
If you have Underscore.js, you can use:
var newArray = _.zip(x, y);

merge two arrays (keys and values) into an object [duplicate]

This question already has answers here:
Merge keys array and values array into an object in JavaScript
(14 answers)
Closed 9 years ago.
Is there a common Javascript/Coffeescript-specific idiom I can use to accomplish this? Mainly out of curiosity.
I have two arrays, one consisting of the desired keys and the other one consisting of the desired values, and I want to merge this in to an object.
keys = ['one', 'two', 'three']
values = ['a', 'b', 'c']
var r = {},
i,
keys = ['one', 'two', 'three'],
values = ['a', 'b', 'c'];
for (let i = 0; i < keys.length; i++) {
r[keys[i]] = values[i];
}
console.log(r);
.as-console-wrapper { max-height: 100% !important; top: 0; }
keys = ['one', 'two', 'three']
values = ['a', 'b', 'c']
d = {}
for i, index in keys
d[i] = values[index]
Explanation:
In coffeescript you can iterate an array and get each item and its position on the array, or index.
So you can then use this index to assign keys and values to a new object.
As long as the two arrays are the same length, you can do this:
var hash = {};
var keys = ['one', 'two', 'three']
var values = ['a', 'b', 'c']
for (var i = 0; i < keys.length; i++)
hash[keys[i]] = values[i];
console.log(hash['one'])
console.log(hash.two);

Categories

Resources