배열에서 서로 다른 인덱스의 두 수를 뽑아 더해 배열로 출력하는 문제 해답
여기서 테스트케이스 출력과 result 가
배열과 객체인 경우에 같은지 확인하려면
JSON.stringify 사용
<script>
const data = [
{
input: [1, 2, 3, 4, 5],
output: [3, 4, 5, 6, 7, 8, 9],
},
{
input: [10, 20, 30, 40],
output: [30, 40, 50, 60, 70],
},
{
input: [-5, 0, 5, 10],
output: [-5, 0, 5, 10, 15],
},
{
input: [1, 1, 2, 2, 3],
output: [2, 3, 4, 5],
},
{
input: [100, 200, 300, 400],
output: [300, 400, 500, 600, 700],
},
{
input: [0, 1, 2, 3],
output: [1, 2, 3, 4, 5],
},
{
input: [1, -1, 2, -2],
output: [-3, -1, 0, 1, 3],
},
{
input: [7, 8, 9, 10],
output: [15, 16, 17, 18, 19],
},
{
input: [1, 2, 3, 4],
output: [3, 4, 5, 6, 7],
},
{
input: [2, 4, 6, 8],
output: [6, 8, 10, 12, 14],
},
];
data.forEach((item) => {
const inputData = item.input;
const result = [];
for (let i = 0; i < inputData.length - 1; i++) {
for (let j = i + 1; j < inputData.length; j++) {
result.push(inputData[i] + inputData[j]);
}
}
const sortedUniqueResult = [...new Set(result)].sort((a, b) => a - b);
console.log(sortedUniqueResult);
console.log(
JSON.stringify(sortedUniqueResult) === JSON.stringify(item.output)
);
});
</script>
JSON.stringify()
기본적인 사용법
그냥 stringify 인자로 배열이나 객체 넘겨줌
const obj = { name: "John", age: 30, city: "New York" };
const jsonString = JSON.stringify(obj);
console.log(jsonString);
// 출력: {"name":"John","age":30,"city":"New York"}
stringify의 인자
두 번째 인자: replacer 함수
replacer 함수를 사용하면 변환 과정을 세밀하게 제어할 수 있다
const obj = { a: 1, b: 2, c: 3 };
const replacer = (key, value) => {
if (typeof value === "number") {
return value * 2;
}
return value;
};
console.log(JSON.stringify(obj, replacer));
// 출력: {"a":2,"b":4,"c":6}
세 번째 인자: space
space 인자를 사용하면 JSON 문자열의 들여쓰기를 제어할 수 있다
const obj = { name: "John", age: 30, hobbies: ["reading", "music"] };
console.log(JSON.stringify(obj, null, 2));
/*
출력:
{
"name": "John",
"age": 30,
"hobbies": [
"reading",
"music"
]
}
*/
toJSON 메서
객체에 toJSON 메서드를 정의하면 JSON.stringify()가 이를 사용
const date = new Date();
console.log(JSON.stringify(date));
// 출력: "2025-02-05T06:00:00.000Z"
const customObj = {
data: "Hidden",
toJSON() {
return { customData: "Visible" };
}
};
console.log(JSON.stringify(customObj));
// 출력: {"customData":"Visible"}